diff --git a/RemoveUsers.ps1 b/RemoveUsers.ps1 index 57d0851..52342c4 100644 --- a/RemoveUsers.ps1 +++ b/RemoveUsers.ps1 @@ -4,7 +4,7 @@ $SafeUsers = "Public", "Default", "Default.migrated", "juser" #User profiles to ##### $UsersToRemove = Get-ChildItem "C:\Users" |? {$_.psiscontainer -and $_.lastwritetime -le (get-date).adddays(-$DaysBack)} -$UsersFromReg = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { (-not($_ -match 'S-1-5-18|S-1-5-19|S-1-5-20')) } #Users from registry, ignoring system accounts +$UsersFromReg = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { (-not($_ -match 'S-1-5-18|S-1-5-19|S-1-5-20')) } #Users from registry, ignoring system accounts $Key = $UsersFromReg | Get-ItemProperty -name "ProfileImagePath" @@ -19,7 +19,9 @@ Get-EventLog -LogName "Security" -InstanceId 4624 -ErrorAction "SilentlyContinue $AccountName = $EventMessage.ReplacementStrings[5] $LogonType = $EventMessage.ReplacementStrings[8] - + # Make all usernames lowercase so they group properly in Inventory + $AccountName = $AccountName.ToLower() + # Look for events that contain local or remote logon events, while ignoring Windows service accounts if ( ( $LogonType -in "2", "10" ) -and ( $AccountName -notmatch "^(DWM|UMFD)-\d" ) ) { @@ -43,6 +45,7 @@ Get-EventLog -LogName "Security" -InstanceId 4624 -ErrorAction "SilentlyContinue if (([DateTime]$EventMessage.TimeGenerated.ToString("yyyy-MM-dd")) -ge ([DateTime](get-date).adddays(-$DaysBack))) { $SafeUsers += $AccountName + Write-Output ($AccountName + ' added to SafeUsers') } } @@ -54,12 +57,12 @@ Get-EventLog -LogName "Security" -InstanceId 4624 -ErrorAction "SilentlyContinue foreach ($item in $UsersToRemove) { - if ($SafeUsers.Contains($item.Name) -eq 0 -and (($item.Name).Split("." + ($env:USERDNSDomain).Split(".")[0])[0]).Length -gt 0 -and $SafeUsers.Contains(($item.Name).Split("." + ($env:USERDNSDomain).Split(".")[0])[0]) -eq 0) + if ($SafeUsers -contains $item.Name -eq 0 -and (($item.Name).Split("." + ($env:USERDNSDomain).Split(".")[0])[0]).Length -gt 0 -and $SafeUsers -Contains (($item.Name).Split("." + ($env:USERDNSDomain).Split(".")[0])[0]) -eq 0) { $Key | ForEach-Object { If($_.ProfileImagePath.ToLower() -match $item.Name) { - Write-Output $_.PSPath ' = ' $_.ProfileImagePath + Write-Output ($_.PSPath + ' = ' + $_.ProfileImagePath) Remove-Item $_.PSPath -Recurse -Force takeown /f $_.ProfileImagePath /a /r /d Y > null 2>&1 Remove-Item $_.ProfileImagePath -Recurse -Force