Add Set-StudentEmail script

This commit is contained in:
2026-05-15 10:31:30 +10:00
parent 76933cd8d0
commit 420a964761
+107
View File
@@ -0,0 +1,107 @@
#Requires -Modules ActiveDirectory
<#
.SYNOPSIS
Assigns email addresses to student users in a specified OU.
.DESCRIPTION
Scans all users in the target OU and sets their email address to
[FirstName][Surname]@[Domain]. Existing email addresses are skipped
unless -Force is used.
.PARAMETER OU
The distinguished name of the OU to search.
.PARAMETER Domain
The email domain to use (e.g. niddrieautisticschool.vic.edu.au).
.PARAMETER Force
Overwrite existing email addresses.
.PARAMETER WhatIf
Preview changes without applying them.
.EXAMPLE
.\Set-StudentEmail.ps1
Runs with the default OU and domain.
.EXAMPLE
.\Set-StudentEmail.ps1 -OU "OU=Students,OU=Users,DC=contoso,DC=com" -Domain "contoso.com"
Runs against a custom OU and domain.
.EXAMPLE
.\Set-StudentEmail.ps1 -WhatIf
Preview what changes would be made without applying them.
#>
[CmdletBinding(SupportsShouldProcess)]
param (
[string]$OU = "OU=Student,OU=Users,OU=5362-NiddrieAutistic,DC=curric,DC=niddrieautistic,DC=wan",
[string]$Domain = "niddrieautisticschool.vic.edu.au",
[switch]$Force
)
# Import the Active Directory module
Import-Module ActiveDirectory -ErrorAction Stop
# Retrieve all users in the specified OU
$users = Get-ADUser -Filter * -SearchBase $OU -Properties GivenName, Surname, EmailAddress
if (-not $users) {
Write-Warning "No users found in OU: $OU"
exit
}
Write-Host "Found $($users.Count) user(s) in '$OU'" -ForegroundColor Cyan
Write-Host ""
$updated = 0
$skipped = 0
$errors = 0
foreach ($user in $users) {
$firstName = $user.GivenName
$surname = $user.Surname
# 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 — strip spaces and force lowercase
$email = "$($firstName.Trim())$($surname.Trim())@$Domain".ToLower()
# Check if email is already set (skip unless -Force)
if ($user.EmailAddress -eq $email -and -not $Force) {
Write-Host "OK: $($user.SamAccountName) 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."
$skipped++
continue
}
# Apply the email address
if ($PSCmdlet.ShouldProcess($user.SamAccountName, "Set email to '$email'")) {
try {
Set-ADUser -Identity $user.DistinguishedName -EmailAddress $email
Write-Host "SET: $($user.SamAccountName) -> $email" -ForegroundColor Green
$updated++
}
catch {
Write-Error "FAIL: Could not update '$($user.SamAccountName)': $_"
$errors++
}
}
}
Write-Host ""
Write-Host "--- Summary ---" -ForegroundColor Cyan
Write-Host "Updated: $updated"
Write-Host "Skipped: $skipped"
Write-Host "Errors: $errors"