Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch parameters and powershell.exe -File parameter

Tags:

powershell

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?

like image 850
olegk Avatar asked Dec 25 '22 18:12

olegk


1 Answers

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

like image 58
Johan de Haan Avatar answered Jan 17 '23 17:01

Johan de Haan