如何使用PowerShell变量作为命令参数?

Gar*_*ary 13 variables parameters powershell

我正在尝试使用变量作为命令的参数,但无法弄明白.比方说,MyCommand将接受两个参数:option1option2他们接受布尔值.我如何使用$ newVar替换选项1或2?例如:

$newVar = "option1"
MyCommand -$newVar:$true
Run Code Online (Sandbox Code Playgroud)

我不断得到一些东西:"无法找到接受参数的位置参数"-System.String option1'.


更具体地说:
这里,CSV文件是不同策略的输出.循环遍历文件中的每个属性,并在我的策略asdf中设置该值; 所以 -$_.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
    }}
}
Run Code Online (Sandbox Code Playgroud)

mjo*_*nor 24

通常使用变量来填充cmdlet参数,您将使用哈希表变量,并使用@展开它

 $newVar = @{option1 = $true}
 mycommand @newVar
Run Code Online (Sandbox Code Playgroud)

添加示例:

$AS_policy1 = @{
Identity = "asdf"
AllowBluetooth = $true
}

Set-ActiveSyncMailboxPolicy @AS_policy1
Run Code Online (Sandbox Code Playgroud)


man*_*lds 7

看看这是否适合您:

 iex "MyCommand -$($newVar):$true"
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了同样的问题,刚刚找到解决方法。解决方案是使用 invoke-Expression: invoke-Expression $mycmd 这使用 $mycmd-string,替换变量并将其作为具有给定参数的 cmdlet 执行