从非PowerShell终端向PowerShell脚本传递布尔参数的方法
解决从Bash调用PowerShell脚本时布尔参数的传递问题
方法1:修改PowerShell脚本的参数处理逻辑
直接在脚本内部将传入的字符串参数转换为布尔值,避免依赖外部终端的类型传递:
修改脚本的参数定义,先接收字符串类型,再在脚本内转换:
[CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $runtime, [Parameter()] [ValidateSet('true', 'false', '1', '0')] # 限制输入有效值 [string] $singleFile = 'true' ) # 转换为布尔类型 $singleFileBool = [bool]::Parse($singleFile.ToLower()) # 也可以用更宽松的判断逻辑兼容更多输入 # $singleFileBool = $singleFile -in 'true', '1', 'yes'
调用时直接传字符串即可:
pwsh MyScript.ps1 win-x64 false
方法2:通过-Command参数用PowerShell语法传递布尔值
在Bash中调用时,使用pwsh -Command执行脚本,直接传递PowerShell原生布尔值(注意Bash对$的转义处理):
# 用单引号包裹命令,避免Bash解析$符号 pwsh -Command './MyScript.ps1 win-x64 $false' # 用双引号时需转义$ pwsh -Command "./MyScript.ps1 win-x64 \$false"
这种方式下,$false会被PowerShell直接识别为布尔类型,无需额外转换。
方法3:改用整数类型接收参数
如果习惯用0/1传递布尔含义,可以把脚本参数类型改为[int],再转换为布尔值:
脚本修改:
[CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string] $runtime, [Parameter()] [int] $singleFile = 1 ) $singleFileBool = [bool]$singleFile
调用时传递数字:
pwsh MyScript.ps1 win-x64 0
内容的提问来源于stack exchange,提问作者void.pointer
相关产品推荐
相关产品推荐

