I have this powershell script named testSwitch.ps1:
param(
[switch] $s
)
Return 's= ' + $s
When I invoke this script directly in PowerShell like this:
.\testSwitch.ps1 -s
The output is
s= True
And it outputs False when the switch is missing. But when I try to invoke the same script with this C# code:
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());
}
the output is:
s= False
It seems that the CommandParameter always interprets switch parameters as false, unlike the PowerShell command-line interpreter. The frustrating thing is that this causes the script to see a value of false for the [switch] parameter without throwing any exceptions about not specifying a value. As opposed to a [bool] parameter, which will throw an exception if you do not provide a value in the CommandParameter constructor.