通常,如果您希望将switch参数的指定推迟到某个变量,则可以将表达式传递给switch参数,如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或switch并进行转换?这是否意味着从其他系统(例如构建系统)调用Powershell脚本时,有必要构造复杂的流控制结构来确定是否在命令字符串中包含开关或忽略它?这似乎很乏味且容易出错,这使我相信事实并非如此。
最佳答案
此行为已被记录为connect上的错误。这是一种解决方法:
powershell ./test.ps1 -source test.ps1 -dest test.copy.ps1 -test:$true
关于powershell - Powershell:在命令行中调用Powershell时,如何传递变量以切换参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367685/