4

According Microsoft:

In rare cases, you might need to provide a Boolean value for a switch parameter. To provide a Boolean value for a switch parameter in the value of the File parameter, enclose the parameter name and value in curly braces, such as the following: -File .\Get-Script.ps1 {-All:$False}

I have a simple script:

[CmdletBinding()] 
Param
(
    [switch] $testSwitch
)
$testSwitch.ToBool()

Next I am trying to run it this way:

powershell -file .\1.ps1 {-testSwitch:$false}

As result I receive an error: enter image description here

But if believe Microsoft it should work.

If I delete [CmdletBinding] attribute this error will not occur, but for some reasons $testSwitch.ToBool() returns False despite whether I pass $True or $False.

Why? What are the reasons of this behaviour?

1
  • This works for plain booleans, too. Commented Sep 7, 2018 at 18:14

2 Answers 2

8

The workaround is to not use the -File parameter:

c:\scripts>powershell.exe .\test.ps1 -testswitch:$true
True
c:\scripts>powershell.exe .\test.ps1 -testswitch:$false
False

enter image description here

It is also an active bug on Microsoft Connect

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

1 Comment

There is a difference between calling powershell from a powershell shell or from a cmd shell, and according to the screen capture and to the quoted text in the question the OP is calling it from a powershell, so this renders you answer almost unuseful.
2

There are ways to make this work, for instance expanding the string:

[CmdletBinding()]
Param(
  [Parameter()]$testSwitch
)

$ExecutionContext.InvokeCommand.ExpandString($testSwitch)

However, you don't really need to do that. Simply run the script with or without the switch and check for the presence of the switch parameter:

[CmdletBinding()]
Param(
  [switch][bool]$testSwitch
)

$testSwitch.IsPresent

Demonstration:

C:\>powershell -File .\test.ps1 -testSwitch
True

C:\>powershell -File .\test.ps1
False

3 Comments

I really need to specify $true or $false. There are a resons for this.
What this command actually do - $ExecutionContext.InvokeCommand.ExpandString($testSwitch)?
@olegk Basically, it expands (PowerShell) expressions and variables in a string.

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.