简体   繁体   中英

How to run powershell command with parameter name is variable

I need to run the same command Get-QadUser and Set-QadUser to one property and his value but my property is a variable.

my code (Set doesn't work !) :

$property = 'MobilePhone' # OK
$value = ($User | get-QadUser -IncludedProperties $property).$property # OK
$user | Set-QadUser -$PropertyName $NewValue # NOK

You can use PowerShell feature called Splatting in this case as explained by Don Jones himself here: Windows PowerShell: Splatting .

In this you can define the parameters as a dictionary object of Property and Value pairs as below:

$parameters = @{$FirstPropertyName = $FirstValue; $SecondPropertyName = $SecondValue; $ThirdPropertyName = $ThirdValue}

Then you can pass this to your cmdlet using @ operator as shown below:

Set-QadUser @parameters

Your complete working script will look as below:

$property = 'MobilePhone' # OK
$value = ($User | get-QadUser -IncludedProperties $property).$property # OK

$parameters = @{$PropertyName = $NewValue}
$user | Set-QadUser @parameters # OK

Edit: I failed to notice earlier that PetSerAl already gave the answer in comments. I hope this answer also adds value overall.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM