Compare commits

..

16 Commits

Author SHA1 Message Date
2a2d852cd0 email fix script 2026-01-22 11:46:52 -06:00
poslop
77cdf5422e log sid and profilePath 2026-01-15 15:48:57 -06:00
poslop
42c7892125 Fix sidItem 2026-01-15 15:35:36 -06:00
poslop
48090ea75c clean up csr notes 2026-01-14 16:21:09 -06:00
poslop
b62ab99c80 csr image example 2026-01-14 16:08:09 -06:00
poslop
e61977c8cd moved tar.gz 2026-01-14 15:57:30 -06:00
poslop
f6d65f6e4a csr registry entry 2026-01-14 15:56:09 -06:00
poslop
61aef331f2 cleaned logging 2026-01-14 15:30:16 -06:00
poslop
d981edea9c corrected ForegroundColor flag 2026-01-14 15:22:39 -06:00
poslop
813fc74972 added more reg 2026-01-14 15:19:58 -06:00
poslop
5d929a7ff0 readme 2026-01-14 12:49:14 -06:00
poslop
3d766fea24 Combined Scripts projects 2026-01-14 12:42:42 -06:00
poslop
db0eacbfa0 Cleaned variable names 2026-01-14 12:20:41 -06:00
poslop
b21f669ffd indent 2026-01-14 12:17:13 -06:00
poslop
7b121a4f2f cleaned string variables 2026-01-14 12:14:02 -06:00
poslop
80a46f75d0 added runtime console logs 2026-01-14 12:11:43 -06:00
14 changed files with 380 additions and 63 deletions

View File

@@ -0,0 +1,64 @@
#### Readme is AI generated with Ollama deepseek-r1:32b ;)
<details type="reasoning" done="true" duration="86">
<summary>Thought for 86 seconds</summary>
> Okay, I need to write a Readme file for this PowerShell script. Let me first understand what the script does.
>
> So, looking at the code, it's using Get-CimInstance to retrieve user profiles on a computer. It then processes each profile, checking if they're system accounts or in an exclusion list. If not, and if they've been inactive beyond $InactiveDays (set to 14), it deletes them.
>
> The script is designed to run with high impact, so probably needs admin rights. The user has excluded "Administrator" and "Example Profile" by default.
>
> I should start the Readme with a title like "User Profile Cleanup Script." Then explain what it does: automates cleaning up unused local user profiles based on inactivity.
>
> Next, I'll outline features. It checks last use time or login date, excludes certain users, handles errors, and works for both domain and local accounts.
>
> For prerequisites, the script needs to run as admin because of high impact operations. Also, it uses CIM cmdlets which are standard in PowerShell on Windows.
>
> How to use section: Save as .ps1, run with PS as admin. Maybe mention excluding specific users by modifying $ExcludedUserNames.
>
> Parameters and settings: Explain each variable like ExcludedUserNames, InactiveDays, etc. Mention that wildcard * can be used for exclusion patterns.
>
> Important notes include not running it on production without testing, backing up profiles if needed, and ensuring exclusions are correctly set to avoid deleting necessary accounts.
>
> Troubleshooting should cover common issues like access denied (run as admin), no profiles found (check inactivity days setting or exclusions), errors during deletion (maybe profile is loaded).
>
> Contact info: Suggest reaching out via email for questions.
>
> I think that covers the main points. I'll structure each section clearly, using bullet points where possible for readability.
</details>
# User Profile Cleanup Script Readme
## Overview
This PowerShell script automates the process of identifying and removing inactive or unused user profiles on a Windows computer. It is designed to help maintain system performance by eliminating unnecessary files associated with old or unused accounts.
## Features
- **Identifies Inactive Profiles:** The script calculates the number of days since the last login or profile use and compares it against a specified threshold (`$InactiveDays`).
- **Exclusion List:** Certain user accounts can be excluded from deletion based on predefined criteria.
- **Error Handling:** Robust error handling ensures that issues during profile cleanup are reported, preventing potential data loss or system instability.
- **High Impact Operations:** The script is configured to run with high impact operations, ensuring it operates with the necessary privileges.
## Prerequisites
1. **Administrator Privileges:** The script must be executed with administrator privileges due to its high impact operations.
2. **PowerShell Environment:** Requires a PowerShell environment on Windows capable of running CIM cmdlets.
3. **Local User Profiles:** Works best when dealing with local user profiles, though it can handle domain accounts as well.
## How to Use
### Step 1: Save the Script
Download or copy the script into a `.ps1` file.
### Step 2: Review and Modify Settings
Before execution:
- **Excluded User Names:** Adjust the `$ExcludedUserNames` array to include any user accounts you wish to protect from deletion. This can include wildcard patterns (e.g., `"Example*"`).
- **Inactive Days Threshold:** Set `$InactiveDays` to determine how many days of inactivity are required before a profile is eligible for deletion.
### Step 3: Execute the Script
Run PowerShell as an administrator and execute the script:
```powershell
.\UserProfileCleanup.ps1
```
If you get a policy error about not being able to execute the script copy and run the contents of [ExecutionPolicy](/scripts/ExecutionPolicy.md)

View File

@@ -0,0 +1,107 @@
#Requires -RunAsAdministrator
[cmdletbinding(ConfirmImpact = 'High', SupportsShouldProcess=$True)]
# CHANGE ME
# Change these settings
$ExcludedUserNames = @("Administrator", "Example Profile")
$InactiveDays = 14
$profilesFound = 0
$ComputerName = $env:computername
Try {
$profiles = Get-CimInstance -Class Win32_UserProfile
} Catch {
Write-Warning "Failed to retreive user profiles on $ComputerName"
Exit
}
ForEach ($profile in $profiles) {
$sid = New-Object System.Security.Principal.SecurityIdentifier($profile.SID)
$account = $sid.Translate([System.Security.Principal.NTAccount])
$accountDomain = $account.value.split("\")[0]
$accountName = $account.value.split("\")[1]
$profilePath = $profile.LocalPath
$loaded = $profile.Loaded
$lastUseTime = $profile.LastUseTime
$isExcluded = $False
$special = $profile.Special
# Check if the account is special/system account
If ($special) {continue}
# Check if the account is Excluded or not
ForEach ($eun in $ExcludedUserNames) {
If($eun -ne [string]::Empty -And -Not $eun.Contains("*") -And ($accountName.ToLower() -eq $eun.ToLower())){
$isExcluded = $True
break
}
If($eun -ne [string]::Empty -And $eun.Contains("*") -And ($accountName.ToLower() -Like $eun.ToLower())){
$isExcluded = $True
break
}
}
# Continue if excluded
If($isExcluded) {
Write-Host "`nProfile $accountName was excluded!" -ForegroundColor Blue
continue
}
#Calculation of the login date
$lastLoginDate = $null
If ($accountDomain.ToUpper() -eq $ComputerName.ToUpper()) {$lastLoginDate = [datetime]([ADSI]"WinNT://$ComputerName/$accountName").LastLogin[0]}
#Calculation of the unused days of the profile
$profileUnusedDays=0
If (-Not $loaded){
If($lastLoginDate -eq $null){ $profileUnusedDays = (New-TimeSpan -Start $lastUseTime -End (Get-Date)).Days }
Else{$profileUnusedDays = (New-TimeSpan -Start $lastLoginDate -End (Get-Date)).Days}
}
If($InactiveDays -ne [uint32]::MaxValue -And $profileUnusedDays -le $InactiveDays){
Write-Host "`nSkipping ""$account"" as it is recently used." -ForegroundColor Blue
Write-Host "Account SID: $sid"
Write-Host "Special system service user: $special"
Write-Host "Profile Path: $profilePath"
Write-Host "Loaded : $loaded"
Write-Host "Last use time: $lastUseTime"
If ($lastLoginDate -ne $null) { Write-Host "Last login: $lastLoginDate" }
Write-Host "Profile unused days: $profileUnusedDays"
continue}
$profilesFound ++
If ($profilesFound -gt 1) {Write-Host "`n"}
Write-Host "`nStart deleting profile ""$account"" on computer ""$ComputerName"" ..." -ForegroundColor Red
Write-Host "Account SID: $sid"
Write-Host "Special system service user: $special"
Write-Host "Profile Path: $profilePath"
Write-Host "Loaded : $loaded"
Write-Host "Last use time: $lastUseTime"
If ($lastLoginDate -ne $null) { Write-Host "Last login: $lastLoginDate" }
Write-Host "Profile unused days: $profileUnusedDays"
If ($loaded) {
Write-Warning "Cannot delete profile because is in use"
Continue
}
Try {
Remove-CimInstance $profile
Write-Host "Profile deleted successfully" -ForegroundColor Green
} Catch {
Write-Host "Error during delete the profile" -ForegroundColor Red
}
}
If($profilesFound -eq 0){
Write-Warning "No profiles to delete"
}

4
ExecutionPolicy.md Normal file
View File

@@ -0,0 +1,4 @@
### Copy Paste and Run to allow PS execution
```powershell
Set-ExecutionPolicy Unrestricted -Scope CurrentUser
```

View File

@@ -0,0 +1,75 @@
Import-Module ActiveDirectory
$EmailDomain = "CHANGE ME.com"
$UPNDomain = "CHANGE ME.com"
$SearchBase = ""
$FixProxyAddresses = $false
$FixUPN = $false
$DryRun = $false
Write-Host "Loading users..." -ForegroundColor Cyan
$Query = @{
LDAPFilter = "(&(objectClass=user)(objectCategory=person))"
Properties = "mail","proxyAddresses","userPrincipalName","sAMAccountName"
}
if ($SearchBase -ne "") { $Query.SearchBase = $SearchBase }
$Users = Get-ADUser @Query
Write-Host ("Users found: {0}" -f $Users.Count) -ForegroundColor Yellow
foreach ($u in $Users) {
$desiredMail = "$($u.sAMAccountName)@$EmailDomain"
$desiredUPN = "$($u.sAMAccountName)@$UPNDomain"
$changes = @()
if ($u.mail -ne $desiredMail) {
$changes += "mail → $desiredMail"
if (-not $DryRun) {
Set-ADUser $u -EmailAddress $desiredMail
}
}
if ($FixProxyAddresses) {
$newPrimary = "SMTP:$desiredMail"
$existing = @()
if ($u.proxyAddresses) { $existing = @($u.proxyAddresses) }
$aliases = $existing | Where-Object { $_ -notlike "SMTP:*" }
$aliases = $aliases | Select-Object -Unique
$newProxy = @($newPrimary) + $aliases
if (-not $existing -or ($existing -join "|") -ne ($newProxy -join "|")) {
$changes += "proxyAddresses updated"
if (-not $DryRun) {
Set-ADUser $u -Replace @{ proxyAddresses = $newProxy }
}
}
}
if ($FixUPN -and $u.userPrincipalName -ne $desiredUPN) {
$changes += "UPN → $desiredUPN"
if (-not $DryRun) {
Set-ADUser $u -UserPrincipalName $desiredUPN
}
}
if ($changes.Count -gt 0) {
Write-Host "$($u.sAMAccountName): $($changes -join ', ')" -ForegroundColor Green
} else {
Write-Host "$($u.sAMAccountName): no changes needed" -ForegroundColor DarkGray
}
}
Write-Host "Done." -ForegroundColor Cyan

1
Readme.md Normal file
View File

@@ -0,0 +1 @@
### Collection of Scripts used for admin tasks on Windows

View File

@@ -1,63 +0,0 @@
$flagFolder = "C:\ProgramData\PrinterHKeyClean"
$flagFile = "${flagFolder}\v1.flag"
if (!(Test-Path $flagFolder)) {
New-Item -Path $flagFolder -ItemType Directory -Force | Out-Null
}
if (Test-Path $flagFile) {
Write-Host "Script has already run. Exiting."
exit
}
$profileListKey = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
$sids = Get-ChildItem $profileListKey
$printerPaths = @(
'\Printers\Connections',
'\Printers\ConvertUserDevModesCount',
'\Software\Xerox\PrinterDriver',
'\Software\Microsoft\Windows NT\CurrentVersion\Devices'
)
$HKLMPrinterPaths = @(
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers',
'HKEY_LOCAL_MACHINE\SOFTWARE\Xerox\PrinterDriver'
)
net stop spooler
foreach ($printerPath in $HKLMPrinterPaths) {
try {
Remove-Item -Path "Registry::$printerPath" -Recurse -Force -ErrorAction Stop
} catch {
Write-Host "Error: $($_.Exception.Message)"
}
}
foreach ($sidKey in $sids) {
$sid = $sidKey.PSChildName
$profilePath = (Get-ItemProperty -Path $sidKey.PSPath -Name ProfileImagePath).ProfileImagePath
foreach ($printerPath in $printerPaths) {
try {
Remove-Item -Path "Registry::HKEY_USERS\$sid$printerPath" -Recurse -Force -ErrorAction Stop
} catch {
Write-Host "Error: $($_.Exception.Message)"
}
}
if (-not $mounted) {
$unloadResult = & reg.exe unload "HKU\$sid" 2>&1
}
}
net start spooler
gpupdate /force
New-Item -Path $flagFile -ItemType File -Force

View File

@@ -0,0 +1,43 @@
# CSR Registry Settings
A common bug is that when a user profile is deleted that contained a printer it is not properly removed from the device. According to this forum post these registry changes help to clear out these printers on logout.
https://serverfault.com/questions/1082240/where-are-these-printers-coming-from-in-devices-and-printers
The HTML is also included in a tar.gz to preserve the original post
### Reg Keys
- These are the keys that need to be added to a group policy or script.
- There are 4 keys that need to be added. They are shown here with this format.
- Each entry is added to the path below
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider
```
```
Name
Type
Data
```
```
InactiveGuidPrinterAge
dword
00000384
ActiveGuidPrinterAge
dword
00000384
InactiveGuidPrinterTrim
dword
00000384
RemovePrintersAtLogoff
dword
00000001
```
#### Notes
I use the **Replace** function and the **Remove when no longer applied** option to delete this key from devices if the policy is ever removed
The registry keys need to be applied under **Computer Configuration** not user
### GPO Example
![Ss](./gpo_example.png)

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

View File

View File

@@ -0,0 +1,86 @@
$flagFolder = "C:\ProgramData\PrinterHKeyClean"
$flagFile = "${flagFolder}\v2.flag"
if (!(Test-Path $flagFolder)) {
New-Item -Path $flagFolder -ItemType Directory -Force | Out-Null
}
if (Test-Path $flagFile) {
Write-Host "Script has already run. Exiting." -ForegroundColor Red
exit
}
$profileListKey = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList'
$sids = Get-ChildItem $profileListKey
$HKUsersPrinterPaths = @(
'\Printers\Connections',
'\Printers\ConvertUserDevModesCount',
'\Software\Xerox\PrinterDriver',
'\Software\Microsoft\Windows NT\CurrentVersion\Devices'
)
$HKLMPrinterPaths = @(
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers',
'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\V4 Connections',
'HKEY_LOCAL_MACHINE\SOFTWARE\Xerox\PrinterDriver'
)
Write-Host "Stopping spooler" -ForegroundColor Yellow
net stop spooler
foreach ($HKLMPrinterPaths in $HKLMPrinterPaths) {
try {
Remove-Item -Path "Registry::${HKLMPrinterPaths}" -Recurse -Force -ErrorAction Stop
Write-Host "Removed local machine key ${HKLMPrinterPaths}" -ForegroundColor Green
} catch {
}
}
foreach ($sidItem in $sids) {
$sid = $sidItem.PSChildName
$profilePath = (Get-ItemProperty -Path $sidItem.PSPath -Name ProfileImagePath).ProfileImagePath
Write-Host "$sid" -ForegroundColor Blue
Write-Host "$profilePath" -ForegroundColor Blue
foreach ($HKUsersPrinterPath in $HKUsersPrinterPaths) {
try {
Remove-Item -Path "Registry::HKEY_USERS\${sid}${HKUsersPrinterPath}" -Recurse -Force -ErrorAction Stop
Write-Host "Removed user profile key HKEY_USERS\${sid}${HKUsersPrinterPath}" -ForegroundColor Green
} catch {
}
}
}
try {
Remove-Item -Path "C:\Windows\System32\spool\PRINTERS" -Recurse -Force
Write-Host "Removed PRINTERS from spooler" -ForegroundColor Green
} catch {
Write-Host "Error Removing PRINTERS from spooler" -ForegroundColor Red
Write-Host "Error: $($_.Exception.Message)"
}
try {
Remove-Item -Path "C:\Windows\System32\spool\V4Dirs" -Recurse -Force
Write-Host "Removed V4Dirs from spooler" -ForegroundColor Green
} catch {
Write-Host "Error Removing V4Dirs from spooler" -ForegroundColor Red
Write-Host "Error: $($_.Exception.Message)"
}
Write-Host "Starting spooler" -ForegroundColor Yellow
net start spooler
Write-Host "Running gpupdate" -ForegroundColor Yellow
gpupdate /force
try {
New-Item -Path $flagFile -ItemType File -Force
Write-Host "created flag at ${flagFile}" -ForegroundColor Green
} catch {
Write-Host "Could not create flag at ${flagFile}" -ForegroundColor Red
Write-Host "Error: $($_.Exception.Message)"
}