Skip to content

Commit 22eccca

Browse files
committed
Add Set-ADUserUPNSuffix function to update user UPN suffixes
1 parent 39b2ba7 commit 22eccca

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
function Set-ADUserUPNSuffix {
2+
[CmdletBinding()]
3+
param(
4+
# The user principal name (UPN) to set the new UPN suffix for. This can be a single UPN or an array of UPNs. This parameter accepts pipeline input from objects that have the UserPrincipalName property.
5+
[Parameter(Mandatory, ValueFromPipelineByPropertyName, Position = 0)]
6+
[ValidateNotNullOrEmpty()]
7+
[string[]]$UserPrincipalName,
8+
9+
# The new UPN suffix to set (do not include the '@' symbol).
10+
[Parameter(Mandatory, Position = 1)]
11+
[ValidateNotNullOrEmpty()]
12+
[string]$NewUPNSuffix
13+
)
14+
15+
begin {
16+
17+
Start-Transcript -Path "$PSScriptRoot\Set-ADUserUPNSuffix.log" -Append -ErrorAction SilentlyContinue
18+
19+
# Stop the script if the Active Directory module is not available.
20+
Import-Module ActiveDirectory -Verbose:$false -ErrorAction Stop
21+
if (-not (Get-Module -Name ActiveDirectory)) {
22+
Write-Error 'Active Directory module is not available. Please ensure it is installed and imported.'
23+
return
24+
}
25+
26+
# Remove the '@' symbol from the new UPN suffix if it was included.
27+
if ($NewUPNSuffix.StartsWith('@')) {
28+
$NewUPNSuffix = $NewUPNSuffix.Substring(1)
29+
}
30+
31+
Write-Information -MessageData "Setting UPN suffix to '$NewUPNSuffix' for $($UserPrincipalName.Count) user(s)." -InformationAction Continue
32+
}
33+
34+
process {
35+
36+
foreach ($ThisUPN in $UserPrincipalName) {
37+
# Check if the user exists
38+
$User = Get-ADUser -Filter { UserPrincipalName -eq $ThisUPN } -ErrorAction SilentlyContinue
39+
if (-not $User) {
40+
Write-Error "A user with the UPN '$ThisUPN' not found."
41+
continue
42+
}
43+
44+
# Set the new UPN suffix
45+
try {
46+
Set-ADUser -Identity $User -UserPrincipalName ($User.UserPrincipalName -replace '@.*$', "@$NewUPNSuffix") -Verbose
47+
Write-Host "Successfully updated UPN for user '$ThisUPN' to '$($User.UserPrincipalName -replace '@.*$', "@$NewUPNSuffix")'." -ForegroundColor Yellow
48+
} catch {
49+
Write-Error "Failed to update UPN for user '$ThisUPN': $_"
50+
}
51+
}
52+
53+
}
54+
55+
end {
56+
Stop-Transcript -ErrorAction SilentlyContinue
57+
Write-Information -MessageData "Finished setting UPN suffix to '$NewUPNSuffix' for $($UserPrincipalName.Count) user(s)." -InformationAction Continue
58+
Write-Information -MessageData "Log file created at '$PSScriptRoot\Set-ADUserUPNSuffix.log'." -InformationAction Continue
59+
60+
# Remove the variables used in the script
61+
Remove-Variable -Name UserPrincipalName, NewUPNSuffix, ThisUPN, User -Verbose:$false -ErrorAction SilentlyContinue
62+
}
63+
}

0 commit comments

Comments
 (0)