给PowerShell脚本传递一个布尔值


谁写脚本的经验再丰富,可能也会有败走麦城的时候。比如写出这样一个test.ps1

param
(
[bool]$Confirm,
[bool]$Force
)
if($Confirm){
    'Confirmed'
}
if($Force){
    'Forced'
}

调用时遇到点小插曲:

PS> .\test.ps1
PS> .\test.ps1 -Confirm $true -Force
C:\Documents\test.ps1 : 缺少参数“Force”的某个参数。请指定一个类型为“System.Boolean”的参数,然后再试一次

所在位置 行:1 字符: 27
+ .\test.ps1 -Confirm $true -Force
+ ~~~~~~
 + CategoryInfo : InvalidArgument: (:) [test.ps1],ParameterBindingException
 + FullyQualifiedErrorId : MissingArgument,test.ps1

PS> .\test.ps1 -Confirm $true -Force $true
Confirmed
Forced

最终达到了期望的结果。我们再换一种调用方式:

PS> powershell.exe .\test.ps1 -Confirm $true -Force $true
C:\test.ps1 : 无法处理对参数“Confirm”的参数转换。无法将值“System.String”转换为类型“System.Boo
lean”。布尔参数仅接受布尔值和数字,例如 $True、$False、1 或 0。
所在位置 行:1 字符: 21
+ .\test.ps1 -Confirm True -Force True
+ ~~~~
 + CategoryInfo : InvalidData: (:) [test.ps1],ParameterBindingArgumentTransformationException
 + FullyQualifiedErrorId : ParameterArgumentTransformationError,test.ps1

上面这样调用的目的,在于脱离PowerShell控制台的上下文,直接在外部应用程序中调用PowerShell.exe,比如你写了一个winform程序,在winform程序中调用PowerShell,千万不要告诉我C#本身可以执行Powershell脚本,因为那样需要引用PowerShell的程序集,而2.0,3.0,4.0的这几个版本很难用一个dll搞定。

上面这样调用错误的原因,$true最终被解释成true字符串,这个字符串默认不能自动转换成布尔类型。其实错误信息给出了提示可以使用1,0:

PS> powershell.exe .\test.ps1 -Confirm 1 -Force 1
Confirmed
Forced

上面这个例子能调用成功,是因为我的上下文还在PowerShell 中,“1”默认被转换成了整数“1”,而整数可以被布尔类型强制类型转换。接下来我要完全脱离PowerShell上下文,在cmd中运行:

c:\> powershell.exe .\test.ps1 -Confirm 1 -Force 1
Confirmed
Forced

结论:跨进程给PowerShell脚本传递布尔类型是,如果遇到解析错误,可以使用0和1代替。

其实更高级更方便的应当是使用switch:

param
(
[switch]$Confirm,
[switch]$Force
)

rather-switch-than-bool

 

本文链接: https://www.pstips.net/pass-boolean-to-script.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注