Advertisement
Guest User

ProfileDeleter.ps1

a guest
Jul 15th, 2023
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.25 KB | None | 0 0
  1. $profilelist = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
  2. foreach ($p in $profilelist)
  3. {
  4. #Get User and Load/Unload times
  5. try
  6. {
  7. $objUser = (New-Object System.Security.Principal.SecurityIdentifier($p.PSChildName)).Translate([System.Security.Principal.NTAccount]).value
  8. }
  9. catch
  10. {
  11. $objUser = "[UNKNOWN]"
  12. }
  13. Remove-Variable -Force LTH,LTL,UTH,UTL -ErrorAction SilentlyContinue
  14. $LTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeHigh -ErrorAction SilentlyContinue).LocalProfileLoadTimeHigh
  15. $LTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeLow -ErrorAction SilentlyContinue).LocalProfileLoadTimeLow
  16. $UTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeHigh -ErrorAction SilentlyContinue).LocalProfileUnloadTimeHigh
  17. $UTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeLow -ErrorAction SilentlyContinue).LocalProfileUnloadTimeLow
  18. $LoadTime = if ($LTH -and $LTL)
  19. {
  20. [datetime]::FromFileTime("0x$LTH$LTL")
  21. }
  22. else
  23. {
  24. $null
  25. }
  26. $UnloadTime = if ($UTH -and $UTL)
  27. {
  28. [datetime]::FromFileTime("0x$UTH$UTL")
  29. }
  30. else
  31. {
  32. $null
  33. }
  34.  
  35. #Grab SID in easy to work with value, put user in string that only pull the username(ignoring domain/device origin)
  36. $SID = $p.PSChildName
  37. $pos = $objUser.IndexOf("\")
  38. $User = $objUser.Substring($pos+1)
  39.  
  40. #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
  41. $ExcludedUsers = "SYSTEM","LOCAL SERVICE","NETWORK SERVICE"
  42.  
  43.  
  44. #Make sure user isn't in the excluded users
  45. if($User -notin $ExcludedUsers)
  46. {
  47. #If the user hasn't been loaded for 30 Days look to delete
  48. if($LoadTime -lt (Get-Date).AddDays(-30))
  49. {
  50. #Create a temp folder for reboot clean-up script to live in
  51. $TempPath = "C:\TEMP"
  52. if(!(Test-Path -PathType Container $TempPath))
  53. {
  54. New-Item -ItemType Directory -Path $TempPath
  55. }
  56.  
  57. #Un-comment confirmation if you'd like to keep older profiles or for de-bugging purposes
  58. #$confirmation = Read-Host "Do you want to remove $User(y/n)"
  59. #if($confirmation -eq 'y')
  60. #{
  61. #Delete SID registry entry
  62. Write-Host "Removing $User from registry..." -ForegroundColor White -BackgroundColor DarkCyan
  63. Get-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$SID" | Remove-Item -Force
  64.  
  65. #Removing CIMInstance - could be moot
  66. Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split(‘\’)[-1] -eq '$User' } | Remove-CimInstance
  67.  
  68. #Clear out user profile folder - ignores error since NTUSER.dat file can't be deleted until reboot
  69. Write-Host "Cleaning up C:\Users\$User..." -ForegroundColor White -BackgroundColor DarkCyan
  70. Remove-Item "C:\Users\$User" -Recurse -Force -ErrorAction SilentlyContinue
  71.  
  72. #Adds user to temporary script used for cleanup on next logon
  73. Write-Host "Adding $User to clean up on next logon...`n" -ForegroundColor White -BackgroundColor DarkCyan
  74. "Remove-Item C:\Users\$User -Recurse -Force" >> 'C:\TEMP\Cleanup.ps1'
  75. #}
  76. }
  77. }
  78.  
  79. }
  80.  
  81.  
  82. #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
  83. if(Test-Path 'C:\TEMP\Cleanup.ps1' -PathType Leaf)
  84. {
  85. #Scheduled task self deletes after running with this command
  86. "Unregister-ScheduledTask -TaskName `"RemoveUserPaths`" -Confirm:`$false" >> 'C:\TEMP\Cleanup.ps1'
  87. #Maeks the temporary script clean itself up
  88. "Remove-Item C:\TEMP\Cleanup.ps1" >> 'C:\TEMP\Cleanup.ps1'
  89.  
  90. #Creating the scheduled task to run at the next logon - $trigger
  91. $trigger = New-ScheduledTaskTrigger -AtLogOn
  92.  
  93. #Creating the scheduled task to execute the powershell script - $action
  94. $action = New-ScheduledTaskAction -Execute 'powershell.exe' `
  95. -Argument ('-ExecutionPolicy Bypass' + `
  96. ' -File "C:\TEMP\Cleanup.ps1"')
  97.  
  98. #Giving the scheduled task the authority to run the script - $principal
  99. $principal = New-ScheduledTaskPrincipal -Id 'CJJ' `
  100. -UserId "NT AUTHORITY\SYSTEM" `
  101. -LogonType ServiceAccount `
  102. -RunLevel Highest
  103.  
  104. #Bundling into a task object to allow for easier assignment - $task
  105. $task = New-ScheduledTask -Description 'Delete removed user profile paths' `
  106. -Action $action `
  107. -Principal $principal `
  108. -Trigger $trigger
  109. #Actual task registration
  110. $task = $task | Register-ScheduledTask -TaskName 'RemoveUserPaths' `
  111. -TaskPath '\Temporary Task' `
  112. -User 'NT Authority\SYSTEM'
  113. }
  114.  
Tags: powershell
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement