Last active
March 31, 2023 18:37
-
-
Save stutstev/59ee1c6284a2740005c3f9571b81f584 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Delete Cached User Profiles | |
| .PARAMETER IgnoreListFile | |
| Specify plain text file containing list of user profile (full / absolute) directory paths to exclude from deletion. | |
| .NOTES | |
| Author : Steven Peguero | |
| Date : 2023-03-31 | |
| License : MIT | |
| #> | |
| Param ( | |
| [Parameter(Mandatory = $False)] | |
| [String] | |
| $IgnoreListFile | |
| ) | |
| $ErrorActionPreference = "Stop" | |
| $ActiveProfiles = (Get-WmiObject -ClassName Win32_ComputerSystem).Username | |
| $AllProfiles = $Null | |
| $TargetProfiles = $Null | |
| $IgnoreProfiles = $Null | |
| # = Start Log => | |
| Start-Transcript -Path "${env:SYSTEMROOT}\Temp\${PSScriptRoot}.log" -ErrorAction SilentlyContinue | |
| # = Get Ignored Profile List => | |
| foreach ($Item in $ActiveProfiles) | |
| { | |
| $Item = $Item -replace "^[a-zA-Z0-9]*\\", "" | |
| $IgnoreProfiles += Get-CimInstance -Class Win32_UserProfile | Where-Object { | |
| $_.LocalPath -like "${env:SYSTEMDRIVE}\Users\${Item}" | |
| } | ForEach-Object { | |
| $_.LocalPath | |
| } | |
| } | |
| $IgnoreProfiles += Get-CimInstance -Class Win32_UserProfile | Where-Object { | |
| $_.LocalPath -like "${env:SYSTEMDRIVE}\Users\Administrator" -or ` | |
| $_.LocalPath -like "${env:SYSTEMDRIVE}\Users\${env:USERNANME}" -or ` | |
| $_.LocalPath -like "${env:SYSTEMROOT}*" | |
| } | ForEach-Object { | |
| $_.LocalPath | |
| } | |
| if ($IgnoreListFile -ne $Null) | |
| { | |
| $IgnoreProfiles += (Get-Content -Path $IgnoreListFile -ErrorAction Stop) | |
| } | |
| # = Remove Ignored Profiles from Target List => | |
| $AllProfiles += Get-CimInstance -Class Win32_UserProfile | |
| $TargetProfiles = $AllProfiles | Where-Object {$IgnoreProfiles -notcontains $_.LocalPath} | |
| # = Process Profile Deletion => | |
| Write-Output "`nActive Users`n------------" | |
| $ActiveProfiles | |
| Write-Output "`nTargeted User Profiles`n----------------------" | |
| $TargetProfiles | ForEach-Object {$_.LocalPath} | |
| $TargetProfiles | Select-Object -Unique | Remove-CimInstance -Verbose -ErrorAction Continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment