如何从命令提示符将布尔值传递给 PowerShell 脚本 [英] How to pass boolean values to a PowerShell script from a command prompt
问题描述
我必须从批处理文件中调用 PowerShell 脚本.脚本的参数之一是布尔值:
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\powershell.exe -NoProfile -File .\RunScript.ps1 -Turn 1 -Unify $false
命令失败并出现以下错误:
The command fails with the following error:
Cannot process argument transformation on parameter 'Unify'. 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:0 char:1
+ <<<< <br/>
+ CategoryInfo : InvalidData: (:) [RunScript.ps1], ParentContainsErrorRecordException <br/>
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,RunScript.ps1
截至目前,我在脚本中使用字符串到布尔值的转换.但是如何将布尔参数传递给 PowerShell?
As of now I am using a string to boolean conversion inside my script. But how can I pass boolean arguments to PowerShell?
推荐答案
当使用 -File
参数时,powershell.exe 似乎没有完全评估脚本参数.特别是,$false
参数被视为字符串值,类似于下面的示例:
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
您可以尝试使用 -Command
而不是使用 -File
,它会将调用评估为脚本:
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
作为 大卫 建议,使用 switch 参数也会更惯用,通过消除显式传递布尔值的需要来简化调用:
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
这篇关于如何从命令提示符将布尔值传递给 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!