我有一个名为 testSwitch.ps1 的 powershell 脚本:
param(
[switch] $s
)
Return 's= ' + $s
Run Code Online (Sandbox Code Playgroud)
当我像这样直接在 PowerShell 中调用这个脚本时:
.\testSwitch.ps1 -s
Run Code Online (Sandbox Code Playgroud)
输出是
s= True
Run Code Online (Sandbox Code Playgroud)
当开关丢失时,它输出 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());
}
Run Code Online (Sandbox Code Playgroud)
输出是:
s= False
Run Code Online (Sandbox Code Playgroud)
与 PowerShell 命令行解释器不同,CommandParameter 似乎总是将开关参数解释为 false。令人沮丧的是,这会导致脚本看到[switch]参数的值为 false,而不会引发任何关于未指定值的异常。与[bool]参数相反,如果您没有在CommandParameter构造函数中提供值,它将引发异常。
奇怪的是,您必须指定 true 作为参数值,如下所示:
command.Parameters.Add(new CommandParameter("s", true));
Run Code Online (Sandbox Code Playgroud)
此外,指定 false 也按预期工作:
command.Parameters.Add(new CommandParameter("s", false));
Run Code Online (Sandbox Code Playgroud)
退货
s= False
Run Code Online (Sandbox Code Playgroud)
所以,我猜在从 C# 调用时,[switch] 参数应该像 [bool] 参数一样对待!