Match-UserPrincipalNamesToMailAttribute.ps1
Description:
Script will find users in the configured OU, and if their UserPrincipalName does not match their mail field, make it match. This is useful for o365/SSO scenarios.
Language:
PowerShell
Usage Type:
Standalone
Script Source:
###################################### # Match-UserPrincipalNamesToMailProperty.ps1 # Author(s): Sean Huggans $Script:Version = "22.12.12.3" ###################################### # Script will find users in the configured OU, # and if their UserPrincipalName does not match # their mail field, make it match. ###################################### # Script Variables ############################## $UserOUToSearch = "OU=Standard Users,OU=MHC-Users,DC=mhc,DC=minneolahealth,DC=com" ###################################### # Script Functions ############################## function Log-Action ($Message, $StampDateTime, $WriteHost) { ################################ # Function Version 19.5.11.4 # Function by Sean Huggans ################################ $LogFile = "install.log" $LogDir = "C:\Temp\$($AppName)" $LogPath = "$($LogDir)\$($LogFile)" New-Item -ItemType directory -Path $LogDir -Confirm:$false -Force | out-null if (($StampDateTime -eq $false) -or ($StampDateTime -eq "no")) { $Message | Out-File $LogPath -Append } else { "[ $(get-date -Format 'yyyy.MM.dd HH:mm:ss') ] $($Message)" | Out-File $LogPath -Append } if ($WriteHost -eq $true) { Write-Host $Message } } ###################################### # Script Execution Logic ############################## Try { [array]$UserObjects = Get-ADUser -Filter * -SearchBase $UserOUToSearch -SearchScope Subtree -Properties mail -ErrorAction Stop | Where-Object {(($_.enabled -eq $true) -and ($_.UserPrincipalName -ne $_.mail))} foreach ($UserObject in $UserObjects) { # Ensure we leave users with no mail attribute alone (blank UPNs could be bad) if (($UserObject.mail) -and ($UserObject.mail.Trim() -ne "")) { Try { Set-ADUser -Identity $UserObject.SamAccountName -UserPrincipalName $UserObject.mail -ErrorAction Stop -Confirm:$false Log-Action -Message "$($UserObject.SamAccountName) - Successfully updated UserPrincipalName to match mail property!" -WriteHost $true } catch { Log-Action -Message "Error 3: $($UserObject.SamAccountName) - Error updating user UPN to $($UserObject.mail) ($($_))" -WriteHost $true } } else { Log-Action -Message "Error 2: $($UserObject.SamAccountName) - User has no mail attribute, skipping!" -WriteHost $true } } } catch { Log-Action -Message "Error 1: $($UserObject.SamAccountName) - Error getting user objects" -WriteHost $true }
Note: that all applications posted here are posted for use, both commercial and non-commercial, free of charge, and as such are provided as-is, without warranty of any kind whatsoever. visuaFUSION, FMSCUG or any other program listed here's author are not responsible for any damages or shortcomings that result from usage of any of these applications.