让PowerShell脚本使用C#代码,然后将参数传递给Main方法
我在technet的一篇博客文章中发现,PowerShell可以使用C代码。 第条: 我找到了使C代码在PowerShell中工作所需的格式,但是如果它没有传递让PowerShell脚本使用C#代码,然后将参数传递给Main方法,c#,powershell,main,C#,Powershell,Main,我在technet的一篇博客文章中发现,PowerShell可以使用C代码。 第条: 我找到了使C代码在PowerShell中工作所需的格式,但是如果它没有传递Main方法一个参数([namespace.class]::Main(foo)),脚本将抛出一个错误 是否有一种方法可以将字符串“on”或“off”传递给main方法,然后根据传递的字符串运行if语句?如果可能的话,你能提供例子和/或链接吗 下面是我目前试图构建代码的方式 $Assem = @( //assemblies go here)
Main
方法一个参数([namespace.class]::Main(foo)
),脚本将抛出一个错误
是否有一种方法可以将字符串“on”或“off”传递给main方法,然后根据传递的字符串运行if语句?如果可能的话,你能提供例子和/或链接吗
下面是我目前试图构建代码的方式
$Assem = @( //assemblies go here)
$source = @"
using ...;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args )
{
if(args == on)
{//post foo }
if(arge == off)
{ //post bar }
}
"@
Add-Type -TypeDefinition $Source -ReferencedAssumblies $Assem
[AlertsOnOff.onOff]::Main(off)
#PowerShell script code goes here.
[AlertsOnOff.onOff]::Main(on)
首先,如果要编译和运行C代码,需要编写有效的C代码。在PowerShell端,如果从PowerShell调用
Main
,则需要向其传递一个参数。PowerShell将自动为您将单个参数放入数组中,但如果您没有参数,它不会插入参数。也就是说,不清楚为什么这是一种主要方法。它不是一个可执行文件。它很可能只有两种静态方法,打开
和关闭
。下面的代码编译并运行,请根据需要进行修改:
$source = @"
using System;
namespace AlertsOnOff
{
public class onOff
{
public static void Main(string[] args)
{
if(args[0] == `"on`")
{
Console.WriteLine(`"foo`");
}
if(args[0] == `"off`")
{
Console.WriteLine(`"bar`");
}
}
}
}
"@
Add-Type -TypeDefinition $Source
[AlertsOnOff.onOff]::Main("off")
# Other code here
[AlertsOnOff.onOff]::Main("on")
我同意迈克的看法。OP的代码看起来是以带有标准主入口点的exe编写的。更直接的做法是将其修改为库。此外,如果在here字符串中使用单引号,则不必转义其中的双引号。:-)