[英]How to use a PowerShell variable as command parameter?
I'm trying to use a variable as a command's parameter but can't quite figure it out.我正在尝试使用变量作为命令的参数,但不太明白。 Let's say
MyCommand
will accept two parameters: option1
and option2
and they accept boolean values.假设
MyCommand
将接受两个参数: option1
和option2
,它们接受 boolean 值。 How would I use $newVar to substitute option 1 or 2?我将如何使用$newVar替代选项 1 或 2? For example:
例如:
$newVar = "option1"
MyCommand -$newVar:$true
I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1' .我不断得到类似“无法找到接受参数 '-System.String option1' 的位置参数”的信息。
More Specifically:进一步来说:
Here, the CSV file is an output of a different policy.在这里,CSV 文件是不同策略的 output。 The loop goes through each property in the file and sets that value in my policy asdf ;
循环遍历文件中的每个属性并在我的策略asdf中设置该值; so
-$_.name:$_.value
should substitute as -AllowBluetooth:true
.所以
-$_.name:$_.value
应该替换为-AllowBluetooth:true
。
Import-Csv $file | foreach-object {
$_.psobject.properties | where-object {
# for testing I'm limiting this to 'AllowBluetooth' option
if($_.name -eq "AllowBluetooth"){
Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
}}
}
Typically to use a variable to populate cmdlet parameters, you'd use a hash table variable, and splat it, using @ 通常使用变量来填充cmdlet参数,您将使用哈希表变量,并使用@展开它
$newVar = @{option1 = $true}
mycommand @newVar
Added example: 添加示例:
$AS_policy1 = @{
Identity = "asdf"
AllowBluetooth = $true
}
Set-ActiveSyncMailboxPolicy @AS_policy1
Nowadays, If you don't mind evaluating strings as commands, you may use Invoke-Expression
:如今,如果您不介意将字符串作为命令求值,您可以使用
Invoke-Expression
:
$mycmd = "MyCommand -$($newVar):$true"
Invoke-Expression $mycmd
看看这是否适合您:
iex "MyCommand -$($newVar):$true"
I had the same Problem and just found out how to resolve it. 我有同样的问题,只是发现了如何解决它。 Solution is to use invoke-Expression: invoke-Expression $mycmd This uses the $mycmd-string, replaces variables and executes it as cmdlet with given parameters
解决方案是使用invoke-Expression:invoke-Expression $ mycmd这使用$ mycmd-string,替换变量并将其作为cmdlet用给定参数执行
I would try with: 我会尝试:
$mycmd = "MyCommand -$($newVar):$true" & $mycmd
result 结果
Can't work because the ampersand operator just execute single commands without prameters, or script blocks. 无法工作,因为&符运算符只执行没有参数或脚本块的单个命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.