6

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.

1 Answer 1

5

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#!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.