From 3d766fea24e76b5c89072ade4f88efcaf4b25cbc Mon Sep 17 00:00:00 2001 From: poslop Date: Wed, 14 Jan 2026 12:42:42 -0600 Subject: [PATCH] Combined Scripts projects --- DeleteOldProfiles/README.md | 64 +++++++++++ .../scripts/DeleteOldProfiles.ps1 | 107 ++++++++++++++++++ ExecutionPolicy.md | 4 + .../PrinterDriverInstall.cmd | 0 .../PrinterDriverInstall.ps1 | 0 .../RemoveHKeyPrinters.cmd | 0 .../RemoveHKeyPrinters.ps1 | 6 +- 7 files changed, 178 insertions(+), 3 deletions(-) create mode 100644 DeleteOldProfiles/README.md create mode 100644 DeleteOldProfiles/scripts/DeleteOldProfiles.ps1 create mode 100644 ExecutionPolicy.md rename PrinterDriverInstall.cmd => PrinterDriverInstall/PrinterDriverInstall.cmd (100%) rename PrinterDriverInstall.ps1 => PrinterDriverInstall/PrinterDriverInstall.ps1 (100%) rename RemoveHKeyPrinters.cmd => RemoveHKeyPrinters/RemoveHKeyPrinters.cmd (100%) rename RemoveHKeyPrinters.ps1 => RemoveHKeyPrinters/RemoveHKeyPrinters.ps1 (94%) diff --git a/DeleteOldProfiles/README.md b/DeleteOldProfiles/README.md new file mode 100644 index 0000000..a1a0777 --- /dev/null +++ b/DeleteOldProfiles/README.md @@ -0,0 +1,64 @@ +#### Readme is AI generated with Ollama deepseek-r1:32b ;) + +
+Thought for 86 seconds +> 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. +
+# 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) diff --git a/DeleteOldProfiles/scripts/DeleteOldProfiles.ps1 b/DeleteOldProfiles/scripts/DeleteOldProfiles.ps1 new file mode 100644 index 0000000..103728e --- /dev/null +++ b/DeleteOldProfiles/scripts/DeleteOldProfiles.ps1 @@ -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" +} diff --git a/ExecutionPolicy.md b/ExecutionPolicy.md new file mode 100644 index 0000000..b75163e --- /dev/null +++ b/ExecutionPolicy.md @@ -0,0 +1,4 @@ +### Copy Paste and Run to allow PS execution +```powershell +Set-ExecutionPolicy Unrestricted -Scope CurrentUser +``` \ No newline at end of file diff --git a/PrinterDriverInstall.cmd b/PrinterDriverInstall/PrinterDriverInstall.cmd similarity index 100% rename from PrinterDriverInstall.cmd rename to PrinterDriverInstall/PrinterDriverInstall.cmd diff --git a/PrinterDriverInstall.ps1 b/PrinterDriverInstall/PrinterDriverInstall.ps1 similarity index 100% rename from PrinterDriverInstall.ps1 rename to PrinterDriverInstall/PrinterDriverInstall.ps1 diff --git a/RemoveHKeyPrinters.cmd b/RemoveHKeyPrinters/RemoveHKeyPrinters.cmd similarity index 100% rename from RemoveHKeyPrinters.cmd rename to RemoveHKeyPrinters/RemoveHKeyPrinters.cmd diff --git a/RemoveHKeyPrinters.ps1 b/RemoveHKeyPrinters/RemoveHKeyPrinters.ps1 similarity index 94% rename from RemoveHKeyPrinters.ps1 rename to RemoveHKeyPrinters/RemoveHKeyPrinters.ps1 index 6fc4e4d..a927b50 100644 --- a/RemoveHKeyPrinters.ps1 +++ b/RemoveHKeyPrinters/RemoveHKeyPrinters.ps1 @@ -38,9 +38,9 @@ foreach ($HKLMPrinterPaths in $HKLMPrinterPaths) { } } -foreach ($sidKey in $sids) { - $sid = $sidKey.PSChildName - $profilePath = (Get-ItemProperty -Path $sidKey.PSPath -Name ProfileImagePath).ProfileImagePath +foreach ($sid in $sids) { + $sid = $sid.PSChildName + $profilePath = (Get-ItemProperty -Path $sid.PSPath -Name ProfileImagePath).ProfileImagePath foreach ($HKUsersPrinterPath in $HKUsersPrinterPaths) { try {