r/PowerShell • • 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

20 comments sorted by

View all comments

Show parent comment

1

u/BlackV May 06 '26

I also hate that section of variable reassignment. This is an existing script I'm reworking and need to clean up any areas those alternate names are in use to get rid of it. Just not made it a high priority yet.

oh 100% Ive been (still am) in that exact position where a massive legacy script needs cleaning

my current was was a huge script with no error handling and logging and missing features

Ive cleaned it up, now its a huge module with cleaner code and with better logging and error handling , but it till missing features (and some version control thrown in there)

next is split out some of the logic to smaller functions with controlled input and output

and add more features (better location handling and group/role handling )

and suddenly its 3 years later :)