如何使用PowerShell变量作为命令参数? [英] How to use a PowerShell variable as command parameter?
问题描述
我正在尝试使用变量作为命令的参数,但无法完全弄清楚.假设MyCommand
将接受两个参数:option1
和option2
,并且它们接受布尔值.如何使用 $ newVar 代替选项1或2?例如:
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. How would I use $newVar to substitute option 1 or 2? For example:
$newVar = "option1"
MyCommand -$newVar:$true
我一直沿用的思路.'找不到一个接受参数'-System.String option1'的位置参数..
更具体地说:
此处,CSV文件是其他策略的输出.循环遍历文件中的每个属性,并在我的策略 asdf 中设置该值;因此-$_.name:$_.value
应该替换为-AllowBluetooth:true
.
More Specifically:
Here, the CSV file is an output of a different policy. The loop goes through each property in the file and sets that value in my policy asdf; so -$_.name:$_.value
should substitute as -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
}}
}
推荐答案
通常情况下,要使用变量来填充cmdlet参数,您将使用哈希表变量,并使用@
Typically to use a variable to populate cmdlet parameters, you'd use a hash table variable, and splat it, using @
$newVar = @{option1 = $true}
mycommand @newVar
添加的示例:
$AS_policy1 = @{
Identity = "asdf"
AllowBluetooth = $true
}
Set-ActiveSyncMailboxPolicy @AS_policy1
这篇关于如何使用PowerShell变量作为命令参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!