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.
How do I pass parameters to PowerShell scripts? Passing arguments in PowerShell is the same as in any other shell: you just type the command name, and then each argument, separated by spaces. If you need to specify the parameter name, you prefix it with a dash like -Name and then after a space (or a colon), the value.
To create a switch parameter in a function, specify the switch type in the parameter definition. Switch parameters are easy to use and are preferred over Boolean parameters, which have a less natural syntax for PowerShell. For example, to use a switch parameter, the user types the parameter in the command.
To run scripts via the command prompt, you must first start up the PowerShell executable (powershell.exe), with the PowerShell location of C:\Program Files\WindowsPowerShell\powershell.exe and then pass the script path as a parameter to it.
Strangely enough, you must specify true as the parameter value, like so:
command.Parameters.Add(new CommandParameter("s", true));
Furthermore, specifying false also works as expected:
command.Parameters.Add(new CommandParameter("s", false));
Returns
s= False
So, I guess [switch] parameters should be treated exactly like [bool] parameters when invoking from C#!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With