diff --git a/scripts/DeleteOldProfiles.ps1 b/scripts/DeleteOldProfiles.ps1 new file mode 100644 index 0000000..f692690 --- /dev/null +++ b/scripts/DeleteOldProfiles.ps1 @@ -0,0 +1,43 @@ +# Define the path to the user profiles directory +$profilesPath = "C:\\Users" + +# Get all user directories (excluding hidden and system directories) +$userDirs = Get-ChildItem -Path $profilesPath -Exclude "Default*", "*Public" | Where-Object { $_.Attributes -notmatch 'Hidden|System' } + +# Define the exclusion list +$exclusionList = @( + "Administrator", + "Default User" +) + +# Determine the cutoff date (14 days ago from today) +$cutoffDate = (Get-Date).AddDays(-14) + +foreach ($userDir in $userDirs) { + # Get the user profile name + $username = $userDir.Name + + # Check if the username is in the exclusion list + if ($exclusionList -contains $username) { + Write-Host "Excluding profile: $username" -ForegroundColor Yellow + continue + } + + # Check for ntuser.dat file to confirm it's a user profile + $ntUserFile = Join-Path -Path $userDir.FullName -ChildPath "ntuser.dat" + if (Test-Path $ntUserFile) { + # Get the last write time of the ntuser.dat file + $lastWriteTime = (Get-Item $ntUserFile).LastWriteTime + + # Determine if the profile should be deleted based on the cutoff date + if ($lastWriteTime -lt $cutoffDate) { + Write-Host "Deleting profile: $username" -ForegroundColor Red + # Delete the user profile directory + Remove-Item -Path $userDir.FullName -Force -Recurse + } else { + Write-Host "Profile still active: $username" -ForegroundColor Green + } + } else { + Write-Host "Skipping profile without ntuser.dat: $username" -ForegroundColor Yellow + } +} diff --git a/scripts/DeleteOldProfilesNetProfile.ps1 b/scripts/DeleteOldProfilesNetProfile.ps1 index 1c35060..bb5ca6d 100644 --- a/scripts/DeleteOldProfilesNetProfile.ps1 +++ b/scripts/DeleteOldProfilesNetProfile.ps1 @@ -10,10 +10,10 @@ $inactiveDate = (Get-Date).AddDays(-$daysInactive) $profiles = Get-WmiObject Win32_UserProfile # Get all user profiles -:Loop ForEach-Object ($profile in $profiles) { +:Loop foreach ($profile in $profiles) { $userFolder = $profile.LocalPath $userName = $profile.LocalPath.Split('\')[-1] # Get the username from the folder path - $nameIsExcluded = false + $nameIsExcluded = $false foreach ($name in $excludedProfiles) { if ($item -eq $userName) {