-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateSamAccountNames.ps1
More file actions
58 lines (48 loc) · 2 KB
/
generateSamAccountNames.ps1
File metadata and controls
58 lines (48 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# csv to get samAccountNames from
$inputCSVPath = "MOCK_DATA.csv"
# csv to put samAccountNames in
$outputCSVPath = "getSamAccountNames_Data.csv"
# load in csv
$users = Import-Csv -Path $inputCSVPath
$output = @()
foreach ($employee in $users) {
if (-not $employee.First_Name -or -not $employee.Last_Name){
Write-Host "Skipping row with missing names." -ForegroundColor Yellow
continue
}
# Handle white spaces and special characters
$firstName = $employee.First_Name.Trim()
$lastName = $employee.Last_Name.Trim()
$cleanFirst = $firstName -replace "[^a-zA-Z0-9]"
$cleanLast = $lastName -replace "[^a-zA-Z0-9]"
# convert to SamAccountName
$baseSamAccountName = ($cleanFirst.Substring(0,1) + $cleanLast).ToLower()
$escapedFilter = $baseSamAccountName.Replace("'","''")
try {
$potentialUsers = Get-ADUser -Filter "SamAccountName -like '$escapedFilter*'" -Properties SamAccountName
$matchingUsers = $potentialUsers | Where-Object {
$_.SamAccountName -match "^$($escapedFilter)\d*$"
}
$matchedNames = ($matchingUsers | Select-Object -ExpandProperty SamAccountName) -join ';'
$output += [PSCustomObject]@{
First_Name = $firstName
Last_Name = $lastName
Deparment = $employee.Department
Title = $employee.Title
Start_date = $employee.Start_Date
MatchedSamAccountNames = $matchedNames
}
} catch {
Write-Host "Failed to get $firstName $lastName $($_.Exception.Message)" -ForegroundColor Red
$output += [PSCustomObject]@{
First_Name = $firstName
Last_Name = $lastName
Department = $employee.Department
Title = $employee.Title
Start_Date = $employee.Start_Date
MatchedSamAccountNames = "Error: $($_.Exception.Message)"
}
}
}
$output | Export-Csv -Path $outputCsvPath -NoTypeInformation
Write-Host "SamAccountNames file has been created from $inputCSVPath. "