I created a script for deletion of old AD accounts (students who are no longer on school). Since student accounts are created in OUs by their start year, the logic was to first deactivate accounts of the last year in July and then in January next year delete those who don’t come complaining their account stopped working (for example they repeated a year and so they need their account for a year longer). This question is about the deletion only.
When I tested the script it worked precisely as intended, but when I set it to get run by a scheduled task, instead of the oldest OU the script deleted still active year, including their home folders, which caused huge issues.
This is the script
$ParentOU = "OU=ZACI-UCTY,DC=trnkova,DC=local" # Parent OU, where we look for the oldest sub-OU
$HomeDirRoot = "\\dc1\zak_home$" # Root path, where home folders are stored
# Getting child OUs
$OUs = @(Get-ADOrganizationalUnit -Filter "Name -like '20*'" -SearchBase $ParentOU -SearchScope OneLevel |
Sort-Object Created)
if ($OUs.Count -eq 0) {
Write-Host "Žádné podřízené OU nebyly nalezeny pod $ParentOU" -ForegroundColor Yellow
exit
}
# Oldest OU
$OldestOU = $OUs[0]
$OUName = ($OldestOU.DistinguishedName -split ",")[0] -replace "OU=",""
$HomeDirPath = Join-Path -Path $HomeDirRoot -ChildPath $OUName
Write-Host "Nejstarší OU k odstranění: $($OldestOU.DistinguishedName)" -ForegroundColor Cyan
Write-Host "Smazání odpovídající složky domovských profilů: $HomeDirPath" -ForegroundColor Cyan
# Getting users in this OU
$Users = Get-ADUser -Filter * -SearchBase $OldestOU.DistinguishedName -SearchScope Subtree
# Users' deletion
foreach ($User in $Users) {
try {
Remove-ADUser -Identity $User -Confirm:$false
Write-Host "Smazán uživatel: $($User.SamAccountName)" -ForegroundColor Green
} catch {
Write-Host "Chyba při mazání uživatele $($User.SamAccountName): $_" -ForegroundColor Red
}
}
# Deletion of the relevant home folder
if (Test-Path $HomeDirPath) {
try {
Remove-Item -Path $HomeDirPath -Recurse -Force
Write-Host "Smazána složka domovských profilů: $HomeDirPath" -ForegroundColor Green
} catch {
Write-Host "Chyba při mazání složky $HomeDirPath - $_" -ForegroundColor Red
}
} else {
Write-Host "Složka domovských profilů $HomeDirPath neexistuje." -ForegroundColor Yellow
}
# OU removal
try {
Set-ADOrganizationalUnit -Identity $OldestOU.DistinguishedName -ProtectedFromAccidentalDeletion:$false -Confirm:$false
Remove-ADOrganizationalUnit -Identity $OldestOU.DistinguishedName -Confirm:$false -Recursive
Write-Host "OU $($OldestOU.DistinguishedName) byla úspěšně smazána." -ForegroundColor Green
} catch {
Write-Host "Chyba při mazání OU $($OldestOU.DistinguishedName): $_" -ForegroundColor Red
}
And this is the xml export of the task:
<?xml version="1.0" encoding="UTF-16"?>
-<Task xmlns="; version="1.4">
-<RegistrationInfo>
<Date>2024-07-17T12:30:29.3805523</Date>
<Author>TRNKOVA\synek</Author>
<Description>Smaže OU s účty žáků aktuálně nejstaršího ročníku</Description>
<URI>\Smazání nejstarší OU s účty žáků</URI>
</RegistrationInfo>
-<Triggers>
-<CalendarTrigger>
<StartBoundary>2024-07-17T12:00:00</StartBoundary>
<ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
<Enabled>true</Enabled>
-<ScheduleByMonth>
-<DaysOfMonth>
<Day>Last</Day>
</DaysOfMonth>
-<Months>
<January/>
</Months>
</ScheduleByMonth>
</CalendarTrigger>
</Triggers>
-<Principals>
-<Principal id="Author">
<UserId>S-1-5-18</UserId>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
-<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
-<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>false</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT2H</ExecutionTimeLimit>
<Priority>7</Priority>
-<RestartOnFailure>
<Interval>PT2H</Interval>
<Count>3</Count>
</RestartOnFailure>
</Settings>
-<Actions Context="Author">
-<Exec>
<Command>powershell.exe</Command>
<Arguments>-ExecutionPolicy Bypass -File "C:\Skripty\Smazání nejstarší OU v ZACI-UCTY společně s profily.ps1"</Arguments>
</Exec>
</Actions>
</Task>
When I run the script manually, it works precisely as it should, but scheduled task skips the first three oldest OUs and deletes the 4th oldest. Any idea why?