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 = [email protected]
User with Apostrophe
user Alias / sAMAccountName = John O'Dea
newAlias = [email protected]
User with either First or Lastname with spaces
user Alias / sAMAccountName = Peter Van Denberg
newAlias = [email protected]
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 }
}
CodePudding user response:
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 }
}
}