UPNUpdate.psm1
<#
=========================================================================== Created by: Rhys M Contact: RhysM.PS@gmail.com PS Gallery: https://www.powershellgallery.com/profiles/RhysM/ Filename: UPNUpdate.psm1 ------------------------------------------------------------------------- Module Name: UPNUpdate =========================================================================== #> function UPNUpdate { Param ( [Parameter(Position = 0, Mandatory = $False)] $SearchBase, [Parameter(Position = 0, Mandatory = $False)] $Individual, [Parameter(Position = 1, Mandatory = $True)] [string]$NewUPN ) if ($SearchBase){ foreach ($SelectedOU in $Searchbase) { $GetOU_Users = Get-ADUser -Filter * -SearchBase $SelectedOU Foreach ($OUAccount in $GetOU_Users) { if ($OUAccount.UserPrincipalName -eq $Null){ $UpdatedUPN = $OUAccount.SamAccountName + "@$NewUPN" Set-ADUser -Identity $OUAccount.DistinguishedName -UserPrincipalName $UpdatedUPN } else{ $null, $OldUPNSuffix = $OUAccount.UserPrincipalName -split '@' # drop String Before @ symbol, use string after it $UpdatedUPN = $OUAccount.UserPrincipalName.Replace($OldUPNSuffix, $NewUPN) Set-ADUser -Identity $OUAccount -UserPrincipalName "$UpdatedUPN" $UpdatedUPN } } } } elseif($Individual){ $GetOU_User = Get-ADUser -Filter "SamAccountName -like '$Individual'" if ($GetOU_User.UserPrincipalName -eq $Null){ $UpdatedUPN = $GetOU_User.SamAccountName + "@$NewUPN" Set-ADUser -Identity $GetOU_User.DistinguishedName -UserPrincipalName $UpdatedUPN } else{ $null, $OldUPNSuffix = $GetOU_User.UserPrincipalName -split '@' $UpdatedUPN = $GetOU_User.UserPrincipalName.Replace($OldUPNSuffix, $NewUPN) Set-ADUser -Identity $GetOU_User -UserPrincipalName "$UpdatedUPN" $UpdatedUPN } } } Export-ModuleMember -Function UPNUpdate |