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
}}
}
To pass a variable to a parameter that expects a reference, you must type cast your variable as a reference. The brackets and parenthesis are BOTH required.
The name of the parameter is preceded by a hyphen ( - ), which signals to PowerShell that the word following the hyphen is a parameter name. The parameter name and value can be separated by a space or a colon character. Some parameters do not require or accept a parameter value.
The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.
You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar' . Once you open cmd.exe, you can execute a PowerShell script like below.
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
See if this works for you:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With