Bassie Bassie - 3 months ago 15
PowerShell Question

How to Use String as a Dynamic Argument Name

I am trying to create a function which can update a given property where the name of the property is passed into the function like so:

function Set-UserProperty {
param (
[String]$Property,
[String]$NewValue
)

Get-ADUser Testy.McGee -Properties $Property
Set-ADUser Testy.McGee -$Property $NewValue
# Set-ADUser Testy.McGee -Description $NewValue # <<<<< THIS WORKS
}

Set-UserProperty -Property "Description" -NewValue "New Description"


I can retrieve users just fine, but when I try setting the new
Description
I get this error:


Set-ADUser : A positional parameter cannot be found that accepts argument
'-Description'.


I also tried calling
Set-ADUser Testy.McGee $Property $NewValue
, but this just results in:


Set-ADUser : A positional parameter cannot be found that accepts argument
'Description'.


From the first error, it looks as though
PowerShell
is trying to execute:

Set-ADUser "Testy.Mcgee" -Description "New Description"
, as it complains about the
'-Description'
argument.

However, when I call that exact line (
Set-ADUser "Testy.Mcgee" -Description "New Description"
) the user is updated in AD.

Am I right in thinking that because I passed the parameter in as a
[string]
I can no longer use this as a parameter-name? If so, is there some other way of achieving this (passing the argument name through a function)?

Answer

Try this:

function Set-UserProperty {
    param (
        [String]$Property,
        [String]$NewValue
    )

    Get-ADUser Testy.McGee -Properties $Property
    $Command = "Set-ADUser Testy.McGee -$Property $NewValue"
    Invoke-Expression $Command
    # Set-ADUser Testy.McGee -Description $NewValue # <<<<< THIS WORKS
}