简体   繁体   中英

Powershell to Update AD proxyAddresses

I am trying proxy address for AD users. I am assuming, its not correctly working part related to the -Add @{proxyAddresses="smtp:"+$_.alias+$proxydomain} .

I have checked proxy address attribute in AD Users. its displaying like below.

smtp:@domain.onmicrosoft.com

script:

 $proxydomain = "@domain.onmicrosoft.com"
    Get-ADUser -Filter {(emailaddress -like "*@contoso.com" -and Enabled -eq $true -and sAMAccountName -like "TYU*")} -SearchBase "OU=IT,DC=contoso,DC=local" -SearchScope Subtree -Properties *  | foreach-object {

    $alias=$_.mail.Split("@")[0]

        if ($_.Proxyaddresses -match $_.alias+$proxydomain  )
    {
        Write-Host "Result: ProxyAddresses value already exists for $($_.displayname); No action taken."
    }

        else
    {
      Set-ADUser -Identity $_.SamAccountName -Add @{proxyAddresses="smtp:"+$_.alias+$proxydomain}

        Write-Host "Result: Added proxyAddresses value to Account"
     }

   }

You start out by assigning the user-part of the primary mail address to a variable $alias :

$alias=$_.mail.Split("@")[0]

But the you refer to $_.alias in the following lines:

if ($_.Proxyaddresses -match $_.alias+$proxydomain  )

This is not going to work, because $_.alias resolves to the value of a property named alias on the ADUser object you're currently processing - and since no AD user attribute with the name alias exists, $_.alias evaluates to $null .

Change the code to evaluate the variable instead and it'll work:

$proxydomain = "@domain.onmicrosoft.com"
Get-ADUser -Filter { (emailaddress -like "*@contoso.com" -and Enabled -eq $true -and sAMAccountName -like "TYU*") } -SearchBase "OU=IT,DC=contoso,DC=local" -SearchScope Subtree -Properties *  | foreach-object {

    # grab user alias
    $alias = $_.mail.Split("@")[0]

    # construct the new address up front and assign it to a single variable
    $newProxyAddress = "$alias$proxydomain"

    # -match is a regex operator, escape appropriately
    if ($_.ProxyAddresses -match [regex]::Escape($newProxyAddress)) {
        Write-Host "Result: ProxyAddresses value already exists for $($_.displayname); No action taken."
    }
    else {
        # Now we only have a single variable that needs to be expanded in the string
        Set-ADUser -Identity $_.SamAccountName -Add @{proxyAddresses = "smtp:$newProxyAddress"}

        Write-Host "Result: Added proxyAddresses value to Account"
    }
}

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