Alban
Alban

Reputation: 3215

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

Upvotes: 5

Views: 3146

Answers (1)

Aman Sharma
Aman Sharma

Reputation: 1990

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.

Upvotes: 5

Related Questions