Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $profilelist = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
- foreach ($p in $profilelist)
- {
- #Get User and Load/Unload times
- try
- {
- $objUser = (New-Object System.Security.Principal.SecurityIdentifier($p.PSChildName)).Translate([System.Security.Principal.NTAccount]).value
- }
- catch
- {
- $objUser = "[UNKNOWN]"
- }
- Remove-Variable -Force LTH,LTL,UTH,UTL -ErrorAction SilentlyContinue
- $LTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeHigh -ErrorAction SilentlyContinue).LocalProfileLoadTimeHigh
- $LTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeLow -ErrorAction SilentlyContinue).LocalProfileLoadTimeLow
- $UTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeHigh -ErrorAction SilentlyContinue).LocalProfileUnloadTimeHigh
- $UTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeLow -ErrorAction SilentlyContinue).LocalProfileUnloadTimeLow
- $LoadTime = if ($LTH -and $LTL)
- {
- [datetime]::FromFileTime("0x$LTH$LTL")
- }
- else
- {
- $null
- }
- $UnloadTime = if ($UTH -and $UTL)
- {
- [datetime]::FromFileTime("0x$UTH$UTL")
- }
- else
- {
- $null
- }
- #Grab SID in easy to work with value, put user in string that only pull the username(ignoring domain/device origin)
- $SID = $p.PSChildName
- $pos = $objUser.IndexOf("\")
- $User = $objUser.Substring($pos+1)
- #Add in your usernames you would like to keep, in this case we have a local admin and the service account registry entries we're making sure to avoid
- $ExcludedUsers = "SYSTEM","LOCAL SERVICE","NETWORK SERVICE"
- #Make sure user isn't in the excluded users
- if($User -notin $ExcludedUsers)
- {
- #If the user hasn't been loaded for 30 Days look to delete
- if($LoadTime -lt (Get-Date).AddDays(-30))
- {
- #Create a temp folder for reboot clean-up script to live in
- $TempPath = "C:\TEMP"
- if(!(Test-Path -PathType Container $TempPath))
- {
- New-Item -ItemType Directory -Path $TempPath
- }
- #Un-comment confirmation if you'd like to keep older profiles or for de-bugging purposes
- #$confirmation = Read-Host "Do you want to remove $User(y/n)"
- #if($confirmation -eq 'y')
- #{
- #Delete SID registry entry
- Write-Host "Removing $User from registry..." -ForegroundColor White -BackgroundColor DarkCyan
- Get-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$SID" | Remove-Item -Force
- #Removing CIMInstance - could be moot
- Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split(‘\’)[-1] -eq '$User' } | Remove-CimInstance
- #Clear out user profile folder - ignores error since NTUSER.dat file can't be deleted until reboot
- Write-Host "Cleaning up C:\Users\$User..." -ForegroundColor White -BackgroundColor DarkCyan
- Remove-Item "C:\Users\$User" -Recurse -Force -ErrorAction SilentlyContinue
- #Adds user to temporary script used for cleanup on next logon
- Write-Host "Adding $User to clean up on next logon...`n" -ForegroundColor White -BackgroundColor DarkCyan
- "Remove-Item C:\Users\$User -Recurse -Force" >> 'C:\TEMP\Cleanup.ps1'
- #}
- }
- }
- }
- #Test to see if any users were deleted, if they were create a scheduled task after next logon to clean up old NTUSER.dat files
- if(Test-Path 'C:\TEMP\Cleanup.ps1' -PathType Leaf)
- {
- #Scheduled task self deletes after running with this command
- "Unregister-ScheduledTask -TaskName `"RemoveUserPaths`" -Confirm:`$false" >> 'C:\TEMP\Cleanup.ps1'
- #Maeks the temporary script clean itself up
- "Remove-Item C:\TEMP\Cleanup.ps1" >> 'C:\TEMP\Cleanup.ps1'
- #Creating the scheduled task to run at the next logon - $trigger
- $trigger = New-ScheduledTaskTrigger -AtLogOn
- #Creating the scheduled task to execute the powershell script - $action
- $action = New-ScheduledTaskAction -Execute 'powershell.exe' `
- -Argument ('-ExecutionPolicy Bypass' + `
- ' -File "C:\TEMP\Cleanup.ps1"')
- #Giving the scheduled task the authority to run the script - $principal
- $principal = New-ScheduledTaskPrincipal -Id 'CJJ' `
- -UserId "NT AUTHORITY\SYSTEM" `
- -LogonType ServiceAccount `
- -RunLevel Highest
- #Bundling into a task object to allow for easier assignment - $task
- $task = New-ScheduledTask -Description 'Delete removed user profile paths' `
- -Action $action `
- -Principal $principal `
- -Trigger $trigger
- #Actual task registration
- $task = $task | Register-ScheduledTask -TaskName 'RemoveUserPaths' `
- -TaskPath '\Temporary Task' `
- -User 'NT Authority\SYSTEM'
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement