I am trying to delete user profiles older than 28 days. I have googled and read everything that I can find but I still am having problems with my script. The scrip below deletes all profiles that are found when what I really must have is only those older than 28 days deleted.
Yes, you are correct GPO is the cleanest way to handle this task, however, my management does not want to use a GPO solution. I am in no position to argue. Here is my code if someone could please tell me where my mistake is.
#The list of accounts, which profiles must not be deleted
$date = $(Get-Date).ToString("dd.MM.yyyy")
$output0="$ENV:SystemDrive\ProgramData\Company\Logs\computer_Profilloeschung_delete_gefundenen_userprofiles_$date.log"
$output="$ENV:SystemDrive\ProgramData\Company\Logs\computer_Profilloeschung_delete_old_userprofiles_$date.log"
$output1="$ENV:SystemDrive\ProgramData\Company\Logs\computer_Profilloeschung_kein_Profile_zum_loescheng_$date.log"
$ExcludedUsers ='NETZWERKDIENST','LOKALER DIENST','SYSTEM','Administrator','DefaultUser','Public','PIN-RESET', 'defaultuser0','service_bmcdiscover'
$LocalProfiles=Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and (!$_.Loaded) -and $_.CreationTime -lt (Get-Date).AddDays(-28)}
if (($LocalProfile -eq $null))
{
Write-host $LocalProfile.LocalPath -ForegroundColor Magenta
#output file erstellen nur wenn die benoetig sind
Write-Output "" > "$output"
Write-Output "" > "$output0"
foreach ($LocalProfile in $LocalProfiles)
{
$LocalProfile.LocalPath >> "$output0"
if (!($ExcludedUsers -like $LocalProfile.LocalPath.Replace("C:\Users\","")))
{
Write-host $LocalProfile.LocalPath
$Text = "Profile zum Loeschen"
$Text >> "$output"
$LocalProfile.LocalPath >> "$output"
$LocalProfile | Remove-WmiObject
$Text = "$LocalProfile profile deleted"
$Text >> "$output"
Write-host $LocalProfile.LocalPath, "profile deleted” -ForegroundColor Magenta
}
}
} else {
Write-Output "" > "$output1"
$Test1 = "Kein Profile zum Loeschen"
$Test1 >> "$output1"
Write-host "Kein Profile zum Loeschen” -ForegroundColor Magenta
}