Files
Set-StudentEmail/Set-StudentEmail.ps1
T

100 lines
2.7 KiB
PowerShell

#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
[SamAccountName]@[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 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) {
$username = $user.SamAccountName
# Build the email — force lowercase
$email = "$($username.Trim())@$Domain".ToLower()
# Check if email is already set and matches (skip unless -Force)
if ($user.EmailAddress -eq $email -and -not $Force) {
Write-Host "OK: $username already has '$email'" -ForegroundColor DarkGray
$skipped++
continue
}
if ($user.EmailAddress -and -not $Force) {
Write-Warning "SKIP: '$username' already has email '$($user.EmailAddress)'. Use -Force to overwrite."
$skipped++
continue
}
# Apply the email address
if ($PSCmdlet.ShouldProcess($username, "Set email to '$email'")) {
try {
Set-ADUser -Identity $user.DistinguishedName -EmailAddress $email
Write-Host "SET: $username -> $email" -ForegroundColor Green
$updated++
}
catch {
Write-Error "FAIL: Could not update '$username': $_"
$errors++
}
}
}
Write-Host ""
Write-Host "--- Summary ---" -ForegroundColor Cyan
Write-Host "Updated: $updated"
Write-Host "Skipped: $skipped"
Write-Host "Errors: $errors"