Change email format to [username]@domain
This commit is contained in:
+11
-19
@@ -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++
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user