Switch options and powershell.exe -File option

According to Microsoft:

In rare cases, you may need a boolean value for the switch parameter. To provide a Boolean value for the switch parameter in the value of the File parameter, specify the parameter name and value in curly braces, for example: -File. \ Get- Script.ps1 {-All: $ False}

I have a simple script:

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

      

Next, I try to run it like this:

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

      

As a result, I get an error: enter image description here

But according to Microsoft, it should work.

If I remove the attribute [CmdletBinding]

, this error doesn't happen, but for some reason $testSwitch.ToBool()

returns False, regardless of whether I passed $True

or $False

.

Why? What are the reasons for this behavior?

+3


source to share


2 answers


A 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

This is also an active bug on Microsoft Connect

+6


source


There are ways to make this work, like expanding a string :

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

$ExecutionContext.InvokeCommand.ExpandString($testSwitch)

      

However, you don't really need to do this. Just run the script with or without a switch and check for the switch parameter:



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

$testSwitch.IsPresent

      

Demonstration:

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

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

0


source







All Articles