Home > Enterprise >  Powershell Script to swap Proxyaddresses and PrincipalName
Powershell Script to swap Proxyaddresses and PrincipalName

Time:01-28

Been writing script:

foreach ($Username in (Import-Csv -Path "C:\Users\...\nope.csv")) {

    set-aduser $Username.Username -remove @{Proxyaddresses="smtp:[email protected]"}
        Write-Output "remove proxy"
    set-aduser $Username.Username -replace @{userPrincipalName="[email protected]"}
        Write-Output "replace principal"
    set-aduser $Username.Username -add @{Proxyaddresses="smtp:[email protected]"}
        Write-Output "add proxy"

}

the code runs but ends up putting this garbage -> @{Username=###}[email protected] in the attribute Editor.

Any help would be appreciated, been trying different ways for like 8h now.

CodePudding user response:

Basically the double-quotes are expanding the object $UserName however are not allowing you to reference the property UserName of your object. An easy way to get around this is to use the Subexpression operator $( ):

$object = [pscustomobject]@{
    Hello = 'World!'
}

$object.Hello      # => World!
"$object.Hello"    # => @{Hello=World!}.Hello
"$($object.Hello)" # => World!

On the other hand, a much easier solution in this case would be to reference the UserName property while enumerating the collection:

foreach ($UserName in (Import-Csv -Path "C:\Users\...\nope.csv").UserName) {
    $upn = "[email protected]"
    Set-ADUser $UserName -Remove @{ ProxyAddresses = "smtp:[email protected]" }
    Write-Output "Remove ProxyAddresses for $UserName"
    Set-ADUser $UserName -Replace @{ userPrincipalName = $upn }
    Write-Output "Replace UserPrincipalName for $UserName"
    Set-ADUser $UserName -Add @{ ProxyAddresses = "smtp:$upn" }
    Write-Output "Add ProxyAddresses for $UserName"
}
  •  Tags:  
  • Related