How to use a PowerShell variable as command parameter?

被刻印的时光 ゝ 提交于 2019-12-30 04:00:12

问题


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

I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1'.


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
    }}
}

回答1:


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

Added example:

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

Set-ActiveSyncMailboxPolicy @AS_policy1



回答2:


See if this works for you:

 iex "MyCommand -$($newVar):$true"



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5956862/how-to-use-a-powershell-variable-as-command-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!