如何将[switch]参数从C#传递给PowerShell脚本?

时间:2012-04-24 18:39:02

标签: c# powershell

我有这个名为testSwitch.ps1的powershell脚本:

param(
    [switch] $s
)

Return 's= ' + $s 

当我直接在PowerShell中调用此脚本时,如下所示:

.\testSwitch.ps1 -s

输出

s= True

当开关丢失时输出False。但是当我尝试用这个C#代码调用相同的脚本时:

Command command = new Command(@"testSwitch.ps1");

command.Parameters.Add(new CommandParameter("s"));

RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);

    IEnumerable<PSObject> psresults = new List<PSObject>();
    psresults = pipeline.Invoke();
    Console.WriteLine(psresults.ToArray()[0].ToString());
}

输出是:

s= False

与PowerShell命令行解释器不同,似乎CommandParameter始终将switch参数解释为false。令人沮丧的是,这会导致脚本在[switch]参数中看到false值,而不会抛出任何关于不指定值的异常。与[bool]参数相反,如果您未在CommandParameter构造函数中提供值,则会引发异常。

1 个答案:

答案 0 :(得分:3)

奇怪的是,你必须指定true作为参数值,如下所示:

command.Parameters.Add(new CommandParameter("s", true));

此外,指定false也可以按预期工作:

command.Parameters.Add(new CommandParameter("s", false));

返回

s= False

所以,我猜[switch]参数在从C#调用时应该像[bool]参数一样对待!