简体   繁体   中英

Using PowerShell to add the proxyAddresses attribute with specific format?

I need to add new email aliases to the users in the specific OU, with a specific format like:

user Alias / sAMAccountName = First Lastname
newAlias = FLastname@NewBrandX.com

User with Apostrophe
user Alias / sAMAccountName = John O'Dea
newAlias = JOdea@NewBrandX.com

User with either First or Lastname with spaces
user Alias / sAMAccountName = Peter Van Denberg
newAlias = PVanDenberg@NewBrandX.com

However, my script skill is quite limited, so I wonder if anyone can assist in the script modification below:

$newproxy = "@NewBrandX.com"
$userou = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = @{
   Filter      = 'Enable -eq $true'
   SearchBase = $userou
   Properties = 'SamAccountName', 'ProxyAddresses', 'givenName', 'Surname'
}


$users = Get-ADUser @paramGetADUser


Foreach ($user in $users)
{
   $FirstName = $user.givenName.ToLower() -replace '\s', ''
   $LastName = $user.surname.ToLower() -replace '\s', '' -replace "'", ''
   Set-ADUser -Identity $user.samaccountname -Add @{ proxyAddresses = "smtp:" + $FirstName + $LastName + $newproxy }
}

It looks to me like you want a create a new proxy address in format

  • First character of GivenName
  • Surname without apostrophes or spaces
  • followed by "@NewBrandX.com" .

Your code however takes the full GivenName.

To add to the ProxyAddresses array, you need to replace the entire [string[]] array

$newproxy = "@NewBrandX.com"
$userou   = 'OU=Users,OU=Seattle,DC=usa,DC=contoso,DC=com'
$paramGetADUser = @{
   Filter     = 'Enable -eq $true'
   SearchBase = $userou
   Properties = 'ProxyAddresses'  # SamAccountName, GivenName and Surname are returned by default
}


$users = Get-ADUser @paramGetADUser

foreach ($user in $users) {
    $newAddress = ("smtp:{0}{1}$newproxy" -f $user.GivenName.Trim()[0], ($user.Surname -replace "[\s']+").ToLower())
    $proxies    = @($user.ProxyAddresses)
    # test if this user already has this address in its ProxyAddresses attribute
    if ($proxies -contains $newAddress) {
        Write-Host "User $($user.Name) already has '$newAddress' as proxy address" 
    }
    else {
        Write-Host "Setting new proxy address '$newAddress' to user $($user.Name)" 
        $proxies += $newAddress
        # proxyAddresses needs a **strongly typed** string array, that is why we cast the $proxies array with [string[]]
        $user | Set-ADUser -Replace @{ proxyAddresses = [string[]]$proxies }
    }
}

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