From 3d231b757f72be8aedc2cc4e9fe99c6eb4b8f751 Mon Sep 17 00:00:00 2001 From: jessikitty Date: Fri, 15 May 2026 10:58:58 +1000 Subject: [PATCH] Change email format to [username]@domain --- Set-StudentEmail.ps1 | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/Set-StudentEmail.ps1 b/Set-StudentEmail.ps1 index 3d3585b..93c2929 100644 --- a/Set-StudentEmail.ps1 +++ b/Set-StudentEmail.ps1 @@ -6,7 +6,7 @@ .DESCRIPTION Scans all users in the target OU and sets their email address to - [FirstName][Surname]@[Domain]. Existing email addresses are skipped + [SamAccountName]@[Domain]. Existing email addresses are skipped unless -Force is used. .PARAMETER OU @@ -45,7 +45,7 @@ param ( Import-Module ActiveDirectory -ErrorAction Stop # Retrieve all users in the specified OU -$users = Get-ADUser -Filter * -SearchBase $OU -Properties GivenName, Surname, EmailAddress +$users = Get-ADUser -Filter * -SearchBase $OU -Properties EmailAddress if (-not $users) { Write-Warning "No users found in OU: $OU" @@ -60,41 +60,33 @@ $skipped = 0 $errors = 0 foreach ($user in $users) { - $firstName = $user.GivenName - $surname = $user.Surname + $username = $user.SamAccountName - # Skip users missing a first or last name - if ([string]::IsNullOrWhiteSpace($firstName) -or [string]::IsNullOrWhiteSpace($surname)) { - Write-Warning "SKIP: '$($user.SamAccountName)' is missing a first or last name." - $skipped++ - continue - } + # Build the email — force lowercase + $email = "$($username.Trim())@$Domain".ToLower() - # Build the email — strip spaces and force lowercase - $email = "$($firstName.Trim())$($surname.Trim())@$Domain".ToLower() - - # Check if email is already set (skip unless -Force) + # Check if email is already set and matches (skip unless -Force) if ($user.EmailAddress -eq $email -and -not $Force) { - Write-Host "OK: $($user.SamAccountName) already has '$email'" -ForegroundColor DarkGray + Write-Host "OK: $username already has '$email'" -ForegroundColor DarkGray $skipped++ continue } if ($user.EmailAddress -and -not $Force) { - Write-Warning "SKIP: '$($user.SamAccountName)' already has email '$($user.EmailAddress)'. Use -Force to overwrite." + Write-Warning "SKIP: '$username' already has email '$($user.EmailAddress)'. Use -Force to overwrite." $skipped++ continue } # Apply the email address - if ($PSCmdlet.ShouldProcess($user.SamAccountName, "Set email to '$email'")) { + if ($PSCmdlet.ShouldProcess($username, "Set email to '$email'")) { try { Set-ADUser -Identity $user.DistinguishedName -EmailAddress $email - Write-Host "SET: $($user.SamAccountName) -> $email" -ForegroundColor Green + Write-Host "SET: $username -> $email" -ForegroundColor Green $updated++ } catch { - Write-Error "FAIL: Could not update '$($user.SamAccountName)': $_" + Write-Error "FAIL: Could not update '$username': $_" $errors++ } }