boolean linux shell_给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

)

×用微信扫描并分享

暂时没有相关文章。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值