bwe*_*rks 31 parameters powershell cmd type-conversion
通常,如果要将switch参数的规范推迟到某个变量,可以将表达式传递给switch参数,如WhatIf参数所示.
test.ps1
param ( [string] $source, [string] $dest, [switch] $test )
Copy-Item -Path $source -Destination $dest -WhatIf:$test
Run Code Online (Sandbox Code Playgroud)
这使您在使用交换机时具有很大的灵活性.但是,当您使用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
Run Code Online (Sandbox Code Playgroud)
但是,通过时会出现相同的结果-test:true,并且-test:1.为什么这不起作用?不应该Powershell的类型转换系统自动识别这些字符串可以转换为bool或switch,并转换它们吗?
这是否意味着当从其他系统(例如构建系统)调用powershell脚本时,需要构造复杂的流控制结构来确定是否在命令字符串中包含开关,或者省略它?这似乎很乏味且容易出错,这让我相信情况并非如此.
jon*_*n Z 25
此行为已作为连接上的错误提交.这是一种解决方法:
powershell ./test.ps1 -source test.ps1 -dest test.copy.ps1 -test:$true
Run Code Online (Sandbox Code Playgroud)
Mik*_*ard 13
使用交换机的IsPresent属性.例:
function test-switch{
param([switch]$test)
function inner{
param([switch]$inner_test)
write-host $inner_test
}
inner -inner_test:$test.IsPresent
}
test-switch -test:$true
test-switch -test
test-switch -test:$false
True
True
False
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我使用的是函数而不是脚本,所以它更容易测试.
| 归档时间: |
|
| 查看次数: |
43188 次 |
| 最近记录: |