PowerShell的:如何传递变量在命令行调用的PowerShell何时切换参数?(Powersh

2019-07-30 07:22发布

通常情况下,如果要推迟一个开关参数的一些变量的说明,则可以通过一个表达到开关参数,与WhatIf参数看出。

test.ps1

param ( [string] $source, [string] $dest, [switch] $test )
Copy-Item -Path $source -Destination $dest -WhatIf:$test

这可以让你极大的灵活性,交换机工作时。 然而,当你调用PowerShell和CMD.EXE或什么的,你风像这样的东西:

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脚本时(如构建系统),这是需要构建复杂的流程控制结构,以确定是否要包括在命令字符串中的开关,或者忽略它? 这似乎繁琐,容易出错,这使我相信这不是这种情况。

Answer 1:

此行为已提交上的错误连接 。 这是一种解决方法:

powershell ./test.ps1 -source test.ps1 -dest test.copy.ps1 -test:$true


Answer 2:

使用开关的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

顺便说一句,我使用的功能,而不是一个脚本,它会更容易进行测试。



文章来源: Powershell: How do I pass variables to switch parameters when invoking powershell at the command line?