How to pass boolean values to a PowerShell script from a command prompt

前端 未结 10 2913
逝去的感伤
逝去的感伤 2020-12-08 12:46

I have to invoke a PowerShell script from a batch file. One of the arguments to the script is a boolean value:

C:\\Windows\\System32\\WindowsPowerShell\\v1.0         


        
10条回答
  •  无人及你
    2020-12-08 13:23

    It appears that powershell.exe does not fully evaluate script arguments when the -File parameter is used. In particular, the $false argument is being treated as a string value, in a similar way to the example below:

    PS> function f( [bool]$b ) { $b }; f -b '$false'
    f : Cannot process argument transformation on parameter 'b'. Cannot convert value 
    "System.String" to type "System.Boolean", parameters of this type only accept 
    booleans or numbers, use $true, $false, 1 or 0 instead.
    At line:1 char:36
    + function f( [bool]$b ) { $b }; f -b <<<<  '$false'
        + CategoryInfo          : InvalidData: (:) [f], ParentContainsErrorRecordException
        + FullyQualifiedErrorId : ParameterArgumentTransformationError,f
    

    Instead of using -File you could try -Command, which will evaluate the call as script:

    CMD> powershell.exe -NoProfile -Command .\RunScript.ps1 -Turn 1 -Unify $false
    Turn: 1
    Unify: False
    

    As David suggests, using a switch argument would also be more idiomatic, simplifying the call by removing the need to pass a boolean value explicitly:

    CMD> powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify
    Turn: 1
    Unify: True
    

提交回复
热议问题