Compare commits

...

9 Commits

Author SHA1 Message Date
655248304c Update scripts/ExecutionPolicy.md 2025-02-13 15:24:08 -06:00
3937a19ede Update scripts/ExecutionPolicy.md 2025-02-13 15:23:37 -06:00
6e5631da75 Update README.md 2025-02-13 15:22:55 -06:00
3577ab8062 Update README.md 2025-02-13 15:17:41 -06:00
poslop
ae65596a9d Cleaned up 2025-02-13 12:39:12 -06:00
poslop
58d8f17f0e Cleaned up 2025-02-13 12:36:43 -06:00
poslop
05f8c11367 Comments and rearrange 2025-02-13 12:27:00 -06:00
poslop
b98491ed30 Comments and rearrange 2025-02-13 12:18:35 -06:00
poslop
cf8a656c7c Comments and rearrange 2025-02-13 12:17:40 -06:00
3 changed files with 158 additions and 94 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

@@ -1,108 +1,107 @@
#Requires -RunAsAdministrator
[cmdletbinding(ConfirmImpact = 'High', SupportsShouldProcess=$True)]
$UserName = "*"
$ExcludedUserNames = @("Administrator", "Default Profile")
# 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 ($computer in $ComputerName)
{
$profilesFound = 0
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
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 special/system account
If ($special) {continue}
# Check if the account is Excluded or not
If($accountName.ToLower() -Eq $UserName.ToLower() -Or
($UserName.Contains("*") -And $accountName.ToLower() -Like $UserName.ToLower())) {
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 "Profile $accountName was excluded!" continue}
#Calculation of the login date
$lastLoginDate = $null
If ($accountDomain.ToUpper() -eq $computer.ToUpper()) {$lastLoginDate = [datetime]([ADSI]"WinNT://$computer/$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 ""$computer"" ..." -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 {
$profile.Delete()
Write-Host "Profile deleted successfully" -ForegroundColor Green
} Catch {
Write-Host "Error during delete the profile" -ForegroundColor Red
}
# 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
}
}
If($profilesFound -eq 0){
Write-Warning "No profiles to delete"
# 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"
}

View File

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