Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions RemoveUsers.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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"


Expand All @@ -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" ) ) {

Expand All @@ -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')
}

}
Expand All @@ -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
Expand Down