How I can use Add-Type in powershell through command line in order to execute VB.NET or C# (or JScript.net) code?

青春壹個敷衍的年華 提交于 2020-05-16 07:30:52

问题


Here's the MS documentation concerning Add-Type

So I'm trying to add type through command line:

>powershell Add-Type -TypeDefinition "public class T{public static int Add(int a, int b){return (a + b);}}" -Language CSharp

or

>powershell Add-Type -TypeDefinition "@"""public class T{public static int Add(int a, int b){return (a + b);}}"""@" -Language CSharp

or

>powershell Add-Type -TypeDefinition "@"""public class T{public static int Add(int a, int b){return (a + b);}}"""@" -Language CSharp

or

>powershell Add-Type -TypeDefinition @"public class T{public static int Add(int a, int b){return (a + b);}}"@ -Language CSharp

But whatever I try the execution returns an error. Is it possible to add type by calling the powershell through the cmd console? And then execute the added methods?


回答1:


Here's why you can't do what you are doing and the docs specifically show this.

This punctuation is called a Here String. and it serves a specific purpose.

If you did this in a real PowerShell Editor (ISE, VSCode), note that putting all this on one line generates a syntax error.

Proper here string

$Source = @"
public class T
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }
}
"@

This is not proper (will show syntax error highlighting)...

$Source = @"public class T{public static int Add(int a, int b){return (a + b);}}"@

... because these '@""@' must be on separate lines and fully left aligned and nothing can follow the first one on the same line or be in front of the second one on the same line

This does not show syntax error highlighting:

$Source = @"
public class T{public static int Add(int a, int b){return (a + b);}}
"@

... this can be done in the PowerShell console host but not cmd.exe calling powereshell.exe.

The consolehost will not show syntax errors as well as the editors, if at all in this case.

Anytime you are typing code in the consolehost that requires a CRLF or the like, you have to type it that way. Lastly, doing this in cmd.exe would never show PowerShell syntax errors, until you try and run it.

This is all about fully understanding PowerShell syntax and punctuation.

The Complete Guide to PowerShell Punctuation



来源:https://stackoverflow.com/questions/61373052/how-i-can-use-add-type-in-powershell-through-command-line-in-order-to-execute-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!