通常,如果你想将开关参数的规定推迟到某个变量中,你可以将一个表达式传递给该开关参数,如WhatIf参数所示。
test.ps1
param ( [string] $source, [string] $dest, [switch] $test )
Copy-Item -Path $source -Destination $dest -WhatIf:$test
这使你在使用开关时具有很大的灵活性。但是,当你使用cmd.exe或其他东西调用powershell时,你最终会得到像这样的结果:
D:\test>powershell -file test.ps1 -source test.ps1 -dest test.copy.ps1 -test:$true
D:\test\test.ps1 : Cannot process argument transformation on
parameter 'test'. Cannot convert value "System.String" to type "System.Manageme
nt.Automation.SwitchParameter", parameters of this type only accept booleans or
numbers, use $true, $false, 1 or 0 instead.
At line:0 char:1
+ <<<<
+ CategoryInfo : InvalidData: (:) [test.ps1], ParentContainsError
RecordException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,test.ps1
然而,使用-test:true
和-test:1
时得到的结果相同。为什么会这样?Powershell的类型转换系统不应该自动将这些字符串识别为可转换为bool或开关的类型并进行转换吗?这是否意味着当从其他系统(如构建系统)调用PowerShell脚本时,需要构造复杂的流程控制结构来确定命令字符串中是否包含开关,或者省略它?这似乎很繁琐且容易出错,这让我认为不是这种情况。