r/PowerShell • u/andyr354 • May 06 '26
Question AD User sync script advice
Looking for input on what else I should do to tune this script. It is a project of modifying and cleaning up an older script and I think I've mostly got it where I want it. I'm mostly still just worried about it getting hung up on the new-aduser command.
#######################################################################################
## Import Students from PowerSchool to Active Directory
##
##
##
## Output: Users created/disabled/enabled in AD
## Load Modules necessary on First run...
# Import-Module ServerManager
# Add-WindowsFeature RSAT-AD-PowerShell
#######################################################################################
## Log file Variables
$date = Get-Date -f yyyy-MM-dd-HHmm
$log = "C:\Scripts\Logs\$("ExportLog-" + $date).txt"
$InputFile = "C:\folder\students.csv"
$DestDir = "C:\Scripts\CSVs"
$StartTime = Get-Date
## Organizational Unit variable for user maintenance
$BaseStudentOU = "ou=students,ou=GA-Accounts,dc=contoso,dc=ad"
$GraduatedOU = "ou=graduated,ou=students,ou=GA-Accounts,dc=contoso,dc=ad"
## Summary variables
$usersAdded = 0
$usersDisabled = 0
$usersIncomplete = 0
## Functions
. ".\functions\EmailTools.ps1"
Function Write-Log {
param(
[string]$Message,
[ValidateSet("INFO", "WARN", "ERROR", "SUCCESS")]
[string]$Level = "INFO"
)
$Timestamp = Get-Date -Format "HH:mm:ss"
$LogLine = "[$Timestamp] [$Level]`t $Message"
$LogLine | Out-File $log -Append
Write-Host $LogLine # This also prints it to the screen while you watch it run
}
Function Update-StudentGroups {
param(
[Parameter(Mandatory=$true)][string]$SAM,
[Parameter(Mandatory=$true)][string]$Name,
[string]$Grade,
[string]$GradYear,
[string]$SchoolID
)
$GroupsToAddTo = @()
# 1. Add the Graduation Year Group directly from the CSV
if (-not [string]::IsNullOrWhiteSpace($GradYear)) {
$GroupsToAddTo += $GradYear
}
# 2. Add the spelled-out Grade Group using our map
if ($GradeGroupMap.ContainsKey($Grade)) {
$GroupsToAddTo += $GradeGroupMap[$Grade]
}
# 3. Add the Building Group
if ($BuildingGroupMap.ContainsKey($SchoolID)) {
$GroupsToAddTo += $BuildingGroupMap[$SchoolID]
}
# Add the user to each matched group silently
foreach ($Group in $GroupsToAddTo) {
Add-ADGroupMember -Identity $Group -Members $SAM -ErrorAction SilentlyContinue
}
$AddedGroups = $GroupsToAddTo -join ", "
Write-Log -Message "$Name ($SAM) added to groups: $AddedGroups" -Level "INFO"
}
# --- Static Group Mapping Setup ---
# Map PowerSchool numerical grades to AD Group Names
$GradeGroupMap = @{
"12" = @("TwelfthGrade", "HS Students", "OverDrive-Adult")
"11" = @("EleventhGrade", "HS Students", "OverDrive-YoungAdult")
"10" = @("TenthGrade", "HS Students", "OverDrive-YoungAdult")
"9" = @("NinthGrade", "HS Students", "OverDrive-YoungAdult")
"8" = @("EighthGrade", "MS Students", "OverDrive-Juvenile")
"7" = @("SeventhGrade", "MS Students", "OverDrive-Juvenile")
"6" = @("SixthGrade", "MS Students", "OverDrive-Juvenile")
"5" = @("FifthGrade", "OverDrive-Juvenile")
"4" = @("FourthGrade", "OverDrive-Juvenile")
"3" = @("ThirdGrade", "OverDrive-Juvenile")
"2" = @("SecondGrade")
"1" = @("FirstGrade")
"0" = @("Kindergarten")
"-1" = @("PreK")
}
# Define Building mapping
$BuildingGroupMap = @{
"Some Elementary" = "SomeStudents"
"Some other Elementary" = "SomeOtherStudents"
"Another Elementary" = "AnotherStudents"
"Any Elementary" = "AnyStudents"
}
## Finished with functions and static variables, now we can start the main processing
## Test for the existence of the students.csv file in the ftproot
$FileTest = Test-Path $InputFile
## If the file is not there, then exit
If (-Not $FileTest) {
Write-Log -Message "Autosend file not found. Exiting Export." -Level "ERROR"
Exit
}
Else {
$SourceDir = Split-Path $InputFile -Parent # C:\sftproot
$FileName = Split-Path $InputFile -Leaf # students.csv
$robocopyResult = robocopy $SourceDir $DestDir $FileName /mov /IS
$robocopyExitCode = $LASTEXITCODE
if ($robocopyExitCode -ge 8) {
Write-Log -Message "Robocopy failed with exit code $robocopyExitCode. Output: $($robocopyResult -join ' | ')" -Level "ERROR"
Exit
} else {
Write-Log -Message "Robocopy completed successfully moving $FileName. Exit code: $robocopyExitCode" -Level "INFO"
}
## Set variable pointing to the Students.csv file on the FTP server
$CSVPath = Join-Path $DestDir $FileName
## Import the user list from the CSV file
$PSStudentList = Import-Csv -Path $CSVPath -Header GivenName,LastName,sAMAccountName,Grade,NebraskaStateID,Password,SchoolID,Mail,GradYear
## Count the number of students imported
$usersImported = $PSStudentList.count
Write-Log -Message "Processing started on $date " -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message "Creating new users" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
FOREACH ($Person in $PSStudentList) {
###### Check that all necessary fields are included
$Name = ($person.GivenName + " " + $person.LastName)
If ($Person.Password -eq "") {
Write-Log -Message "Please provide a valid Password for $Name, Processing skipped for $Name" -Level "ERROR"
$usersIncomplete += 1
CONTINUE
}
If ($Person.Mail -eq "") {
Write-Log -Message "Please provide a valid Email address for $Name, Processing skipped for $Name" -Level "ERROR"
$usersIncomplete += 1
CONTINUE
}
If ($Person.NebraskaStateID -eq "") {
Write-Log -Message "Please provide a valid StateID for $Name, Processing skipped for $Name" -Level "ERROR"
$usersIncomplete += 1
CONTINUE
}
If ($Person.sAMAccountName -eq "") {
Write-Log -Message "Please provide a valid StudentID for $Name, Processing skipped for $Name" -Level "ERROR"
$usersIncomplete += 1
CONTINUE
}
## Create variables for each attribute for the user
$Firstname = $Person.GivenName
$Lastname = $Person.LastName
$Username = $Person.sAMAccountName
$SAM = $Person.sAMAccountName
$Grade = $person.grade
$EmployeeNumber = $Person.NebraskaStateID
$Password = $Person.Password
$SchoolID = $Person.SchoolID
$Email = $Person.Mail
$Description = "Student Account"
$GradYear = $Person.GradYear
# Build User Principal Name
$UPN=$Email
# Configure the OU to place the student
If ($grade -Like "-1") {
$Container = "PreK"
}
Else {
$Container = $GradYear
}
$OU = "ou=$Container,$BaseStudentOU"
## Create Account in Active Directory
## Test to see if the user is already there
$ADUser = Get-ADUser -LDAPFilter "(sAMAccountName=$Username)"
If ($Null -eq $ADUser) {
New-ADUser -Name $Name -GivenName $Firstname -Surname $Lastname -DisplayName $Name -ChangePasswordAtLogon $false -PasswordNeverExpires $true `
-SamAccountName $SAM -UserPrincipalName $UPN -Path $OU -Description $Description -CannotChangePassword $true `
-AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force) -EmailAddress $Email -EmployeeNumber $EmployeeNumber -Enabled $true `
-Department $GradYear -Company $SchoolID
Write-Log -Message "Created user : $($Name) SAM: $($SAM)" -Level "INFO"
$usersAdded += 1
# CALL FUNCTION FOR NEW USER
Update-StudentGroups -SAM $SAM -Name $Name -Grade $Grade -GradYear $GradYear -SchoolID $SchoolID
}
ElseIf ($ADUser.enabled -eq $false) {
Set-ADUser -Identity $ADUser -Enabled $true
Set-ADAccountPassword -Identity $ADUser -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $Password -Force)
Write-Log -Message "$Name SAM:$SAM has been re-enabled in Active Directory" -Level "INFO"
# Clear stale groups for re-enabled users
$CurrentGroups = Get-ADPrincipalGroupMembership -Identity $SAM | Where-Object { $_.Name -ne "Domain Users" }
if ($CurrentGroups) {
Remove-ADPrincipalGroupMembership -Identity $SAM -MemberOf $CurrentGroups -Confirm:$false -ErrorAction SilentlyContinue
$GroupNames = $CurrentGroups.Name -join ", "
Write-Log -Message "Cleared stale groups for returning student: $Name ($SAM): $GroupNames" -Level "INFO"
}
# CALL FUNCTION FOR RETURNING USER
Update-StudentGroups -SAM $SAM -Name $Name -Grade $Grade -GradYear $GradYear -SchoolID $SchoolID
}
}
##### Disable users that are not in the exported CSV file from PowerSchool
## Get list of current students from Active Directory
$ADStudentList = Get-ADUser -Filter * -SearchBase $BaseStudentOU |Select-Object -Property GivenName,Surname,SamAccountName
$ADStudentList |Export-Csv -Path C:\Scripts\CSVs\ADStudentExport.csv -NoTypeInformation -Force
$PSStudentList |Export-Csv -Path C:\Scripts\CSVs\PSStudentExport.csv -NoTypeInformation -Force
$DisabledUsers = Compare-Object $ADStudentList $PSStudentList -Property samaccountname |Where-Object {$_.SideIndicator -eq '<='}
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message "Disabling Inactive Users in Active Directory" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
## New scripting only disables users who are not already disabled
ForEach ($User in $DisabledUsers) {
# Re-fetch the real AD user to ensure accurate properties
$ADUser = Get-ADUser -Identity $User.SamAccountName -Properties Enabled, Name
if ($ADUser.Enabled -eq $true) {
Write-Log -Message "Disabling User in Active Directory : $($ADUser.Name) SAM: $($ADUser.SamAccountName)" -Level "INFO"
$usersDisabled += 1
Set-ADUser -Identity $ADUser.SamAccountName -Enabled $false
}
}
$GraduatedUsers = Get-ADUser -Filter * -SearchBase $GraduatedOU
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message "Disabling Users in the Graduated OU" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
ForEach ($Graduate in $GraduatedUsers) {
Write-Log -Message "Disabling Graduate : $($Graduate.Name) SAM: $($Graduate.SamAccountName)" -Level "INFO"
Set-ADUser -Identity $Graduate -Enabled $False
}
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message " Summary Statistics " -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message " Total input Records:`t$($usersImported)" -Level "INFO"
Write-Log -Message " Users Added:`t`t$($usersAdded)" -Level "INFO"
Write-Log -Message " Users Disabled:`t$($usersDisabled)" -Level "INFO"
Write-Log -Message " Incomplete Users:`t$($usersIncomplete)" -Level "INFO"
Write-Log -Message " Graduated Users:`t$($GraduatedUsers.Count)" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message "Log File is: $Log" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
Write-Log -Message "Processing completed (on $date): " -Level "INFO"
$EndTime = Get-Date
$ElapsedTime = $EndTime - $StartTime
Write-Log -Message "Execution Time:`t$($ElapsedTime.Minutes) mins, $($ElapsedTime.Seconds) secs" -Level "INFO"
Write-Log -Message "--------------------------------------------" -Level "INFO"
5
Upvotes
5
u/DrDuckling951 May 06 '26
line 228
I would replace it with IsNullOrWhiteSpace to account for both Null and WhiteSpace.
-------------
line 230 - Build a proper hash for the parameter and pass it along. easier to read. Can piggy back on block 194-204.
(see example 4 for what I'm trying to go with. https://learn.microsoft.com/en-us/powershell/module/activedirectory/new-aduser?view=windowsserver2025-ps)
Note, I don't like to enable the account before the start date. Compliance reason. For these account... eh.. go for it.
block 247-252 - not sure what you're trying to do with the stale group. What are the stale groups? PrimaryGroup? Or are you trying to blast all the group except Domain Users? I feel there are better way to approach this... but your script will do the job.
block 263-266 - ....do you not have a database for this task? it's easier to query sql db than CSV compare. It's worth the work in the long run.
block 280-284 - redundant log. Just disable and call it a day.
block 288-296 - I feel I'm missing something. you're disabling the entire AD User objects in the OU. No filtering. Why?
7
u/IT_fisher May 06 '26
First improvement: Sanitize this ASAP, you are leaking too much information about your environment. For example the location of a CSV that has clear text passwords.
What kind of hang ups are you expecting?
1
u/kaffetant May 06 '26
What is the actual question/problem? At first sight, I would add some try catch in many places.
1
u/BlackV May 06 '26 edited May 06 '26
small changes
change to
to be consistent and also means if you import the log using csv and tab delimiter you get a column for time AND info, instead of a combined line (whether that's useful or not?)
related, all the lines like
get rid the all the random extra spaces in
" Graduated Users:t$($GraduatedUsers.Count)"`although I see tabs in there too so i'd personally remove those to be consistent
This is generally poor behavior
you have minimal adds to this so its probably Ok, but have a look at the performance issues around
+=and arrays (which has been improved in 7 but is still slower than direct assignment)with
$BuildingGroupMap[$SchoolID]and$GradeGroupMap[$Grade]you are relying on variables defined in a separate scope (script vs function), the only place its used is in the function, so it makes sense that it lives in the function vs the main body of the script, that way you are not risking scope issues on your datausing
robocopyto move a single fileyou're probably better using
move-itemas a native cmdlet, which will also give you are real file object if you combine that with the-PassThruparameter making these lines lineredundant
and the native error handling that comes with using powerhell cmdlets vs external executables
I hate this so much
you already have all this information in
$Personso why not use$Personinstead of these random single use variablesthis also moves on to splatting as mentioned by DrDuckling9511 there are a few places where splating would improve the readability
all of these statements
whats the
continueachieving there ? when would it not continue?hope some of it is useful
2
u/nlangrs May 06 '26
Use a tool man, like PowerSyncPro. All your problems will fly away. 😂
1
u/importedtea May 06 '26
I’ve done this before and just recently converted mine to create users in the cloud through graph. How long does it take to run on all your students? When I first made mine on prem it took 18 minutes to run on 2-3000 students. Then I found online if you map your AD server as a PSDrive it significantly speeds it up. It then ran in less than 2 minutes. Also, I used to do a csv file and once I finally switched to our sis API it was so much better and less annoying to run. I skimmed your script but if you have other questions, let me know. I’ve been tweaking my script since like 2019.
1
u/Dadarian May 07 '26
Build real tests with Pester.
-2
u/node77 May 06 '26
Run the New-ADuser with predefined parameters that you have. Just make up the data. Why aren’t you using the graph api?