Switch AD lookup from EmployeeID to sAMAccountName

This commit is contained in:
2026-02-25 11:47:44 +11:00
parent a296806e93
commit a402b78499

View File

@@ -1,5 +1,6 @@
# Update-StaffAD.ps1
# Reads Staff_Extract.csv and updates AD email addresses and account status.
# Matches users by sAMAccountName (PAYROLL_REC_NO column).
# Previews all changes before applying them.
# --- Configuration ---
@@ -22,27 +23,23 @@ Write-Host " PREVIEW OF PLANNED CHANGES" -ForegroundColor Cyan
Write-Host "=============================" -ForegroundColor Cyan
foreach ($entry in $Staff) {
$payrollNo = $entry.PAYROLL_REC_NO.Trim()
$samAccount = $entry.PAYROLL_REC_NO.Trim()
$status = $entry.STAFF_STATUS.Trim()
$email = $entry.E_MAIL.Trim()
# Find user in AD by EmployeeID
# Find user in AD by sAMAccountName
try {
$adUser = Get-ADUser -Filter "EmployeeID -eq '$payrollNo'" `
-Properties EmployeeID, EmailAddress, Enabled, SamAccountName, DisplayName `
$adUser = Get-ADUser -Identity $samAccount `
-Properties EmailAddress, Enabled, DisplayName `
-ErrorAction Stop
} catch {
continue
}
if (-not $adUser) {
# User not found in AD, skip
continue
}
$planned = [PSCustomObject]@{
DisplayName = $adUser.DisplayName
SamAccountName = $adUser.SamAccountName
PayrollNo = $payrollNo
SamAccountName = $samAccount
Status = $status
CurrentEmail = $adUser.EmailAddress
NewEmail = $email
@@ -54,8 +51,7 @@ foreach ($entry in $Staff) {
$Changes.Add($planned)
# Display the planned change
Write-Host "`n User : $($planned.DisplayName) ($($planned.SamAccountName))" -ForegroundColor White
Write-Host " Payroll No : $payrollNo"
Write-Host "`n User : $($planned.DisplayName) ($samAccount)" -ForegroundColor White
Write-Host " Status : $status"
if ($planned.WillUpdateEmail) {
@@ -107,8 +103,6 @@ Write-Host "=============================" -ForegroundColor Cyan
foreach ($change in $Changes) {
try {
$adUser = Get-ADUser -Identity $change.SamAccountName -Properties EmailAddress, Enabled
if ($change.WillUpdateEmail) {
Set-ADUser -Identity $change.SamAccountName -EmailAddress $change.NewEmail
Write-Host " [OK] Updated email for $($change.DisplayName): $($change.NewEmail)" -ForegroundColor Green
@@ -116,7 +110,7 @@ foreach ($change in $Changes) {
if ($change.WillDisable) {
Disable-ADAccount -Identity $change.SamAccountName
Write-Host " [OK] Disabled account for $($change.DisplayName) ($($change.Status))" -ForegroundColor Green
Write-Host " [OK] Disabled account for $($change.DisplayName) (status: $($change.Status))" -ForegroundColor Green
}
} catch {