2
我有一個名爲testSwitch.ps1此PowerShell腳本:如何將[switch]參數傳遞給C#中的PowerShell腳本?
param(
[switch] $s
)
Return 's= ' + $s
當我在PowerShell中直接調用這個腳本是這樣的:
.\testSwitch.ps1 -s
輸出是
s= True
,並將其輸出當交換機丟失時會失敗。但是,當我嘗試使用本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
看來,CommandParameter總是解釋開關參數爲假,不像PowerShell命令行翻譯。令人沮喪的是,這會導致腳本看到參數[switch]
的值爲false,而不會拋出任何有關未指定值的例外。與[bool]
參數相反,如果您在CommandParameter
構造函數中未提供值,將會拋出異常。此外
command.Parameters.Add(new CommandParameter("s", true));
,指定假按預期工作也: