Files
skrypty_windows/CleanUserProfiles.ps1
T
2026-07-21 13:30:02 +02:00

66 lines
2.5 KiB
PowerShell

# CleanUserProfiles.ps1
# Wymaga uruchomienia z uprawnieniami Administratora
#Requires -RunAsAdministrator
# 1. Lista SID-ów systemowych do wykluczenia
$ExcludedSIDs = @(
"S-1-5-21-3670944717-3182157424-105470765-500", # Główny Administrator
"S-1-5-18", # Local System
"S-1-5-19", # Local Service
"S-1-5-20" # Network Service
)
# 2. Lista kont egzaminacyjnych i pracownianych do wykluczenia
$ExcludedAccounts = @(
"inf03",
"inf04",
"teoria",
"aud"
)
Write-Host "Rozpoczynam skanowanie i czyszczenie profili użytkowników..." -ForegroundColor Cyan
Write-Host ""
# Pobieramy profile, pomijając systemowe wbudowane (np. folder Default)
$profiles = Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.Special -eq $false }
$deletedCount = 0
foreach ($profile in $profiles) {
$sid = $profile.SID
$path = $profile.LocalPath
$folderName = Split-Path $path -Leaf
# Próba przetłumaczenia numeru SID na przyjazną nazwę konta
$accountName = ""
try {
$sidObj = [System.Security.Principal.SecurityIdentifier]::new($sid)
$ntAccount = $sidObj.Translate([System.Security.Principal.NTAccount])
# Wynik to np. DOMENA\inf03 lub NAZWAKOMPUTERA\inf03, więc odcinamy przedrostek
$accountName = $ntAccount.Value.Split('\')[-1]
} catch {
# Jeśli konto domenowe zostało usunięte z AD i nie da się go przetłumaczyć
$accountName = $folderName
}
# Sprawdzamy, czy SID, nazwa konta lub nazwa folderu znajdują się na listach wykluczeń
if ($sid -in $ExcludedSIDs -or $accountName -in $ExcludedAccounts -or $folderName -in $ExcludedAccounts) {
Write-Host "[Pominięto] $path (Konto na liście wykluczeń)" -ForegroundColor DarkGray
continue
}
Write-Host "[Info] Próba usunięcia: $path (SID: $sid)..." -NoNewline
try {
Remove-CimInstance -InputObject $profile -ErrorAction Stop
Write-Host " SUKCES" -ForegroundColor Green
$deletedCount++
} catch {
Write-Host " BŁĄD" -ForegroundColor Red
Write-Host " Szczegóły: $_" -ForegroundColor Red
Write-Host " (Profil może być w użyciu.)" -ForegroundColor Yellow
}
}
Write-Host ""
Write-Host "[Podsumowanie] Usunięto profili: $deletedCount" -ForegroundColor Cyan