Today I’m going to share a script that detects user profiles on the server that have not been used for a certain number of days (e.g. 60) and deletes them automatically to free up space and keep the server tidy.
- The script is run on a Windows server.
- You can customize the number of days after which unused profiles will be deleted.
- The script saves the deleted profiles to a file
This script can, of course, be executed on many servers, just provide a list of servers on which the script is to be executed on the input.
Script code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# Konfiguracja $daysUnused = 60 # Liczba dni, po których profil jest uznawany za stary $logFile = "C:\Dell\usunieteProfile.txt" # Ścieżka do pliku logu # Pobranie daty z ograniczeniem czasu $limitDate = (Get-Date).AddDays(-$daysUnused) function LogMessage($message) { $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Add-Content -Path $logFile -Value "$timestamp - $message" } # Funkcja do konwersji WMI czasu na obiekt DateTime function Convert-WmiTime($wmiTime) { try { return [DateTime]::ParseExact($wmiTime.Substring(0, 14), "yyyyMMddHHmmss", $null) } catch { return $null } } # Pobranie listy profili użytkowników $profiles = Get-WmiObject -Class Win32_UserProfile | Where-Object { $_.LastUseTime -ne $null -and (Convert-WmiTime $_.LastUseTime) -lt $limitDate } # Przetworzenie znalezionych profili foreach ($profile in $profiles) { $username = $profile.LocalPath -replace '.*\\', '' $lastUsed = Convert-WmiTime $profile.LastUseTime try { # Próbujemy usunąć stary profil Remove-WmiObject -Path $profile.__PATH LogMessage "Usunięto profil użytkownika: $username (Ostatnie użycie: $lastUsed)" Write-Host "Usunięto profil użytkownika: $username (Ostatnie użycie: $lastUsed)" } catch { # Obsługa błędów, jeśli usuwanie profilu nie powiedzie się LogMessage "Błąd podczas usuwania profilu użytkownika: $username - $_" Write-Host "Błąd podczas usuwania profilu użytkownika: $username - $_" } } |