powershell - Powershell:在命令行中调用Powershell时,如何传递变量以切换参数?

标签 powershell parameters type-conversion cmd

通常,如果您希望将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/

相关文章:

reactjs - React - 具有相同路径的路由,但不同的参数会在更新时更改数据

c++ - 混淆克隆传递参数

c++ - 将 long long 转换为 int 如何工作?

sql-server - 写SqlTableData : The given value of type String from the data source cannot be converted to type bit of the specified target column

string - Powershell字符串分割差异

function - 输出参数是否是其值隐式重新初始化的引用?

javascript - countToRandom() 接受参数

powershell - 仅从 csv 文件中删除重复记录

powershell - 将 SecureString 变量传递给只读域 Controller 的 DSC 配置

c# - 将文本框文本转换为整数