Skip to content

Instantly share code, notes, and snippets.

@themaximax
Last active January 16, 2025 06:47
Show Gist options
  • Save themaximax/80f98490298f3c75234c26149aa0b0ea to your computer and use it in GitHub Desktop.
Save themaximax/80f98490298f3c75234c26149aa0b0ea to your computer and use it in GitHub Desktop.
Простой powershell скрипт для удаления старых профилей пользователей с терминального сервера
# указываем сколько дней с момента последнего изменения чтобы считать устаревшим
$dateLimit = 180
# Путь к папкам профилей
$usersPath = "C:\Users"
# список пользователей, которых не трогаем, через запятую в ковычках
$excludeList = "Public", "Default","Administrator", "root", "adm.*", ".NET*", "csb"
# Путь к папке, куда будем бэкапить профили
$backupPath = "E:\BackupUsers"
# Путь к исполняемому файлу WinRAR. Встроенный архиватор PowerShell сыпал ошибки на длинных путях
$winrarPath = "C:\Program Files\WinRAR\WinRAR.exe"
# Проверяем, существует ли WinRAR
if (-not (Test-Path $winrarPath)) {
Write-Error "WinRAR не найден по указанному пути: $winrarPath"
Start-Sleep 5
exit
}
# высчитываем дату устаревания
$dateLimit = $(Get-Date).AddDays(-$dateLimit)
# Получаем список устаревших папок пользователей
$oldFolders = Get-ChildItem -Path $usersPath -Directory -Exclude $excludeList | Where-Object {
$_.LastWriteTime -lt $dateLimit}
# Пребираем полученные папки
ForEach ($userDir in $oldFolders) {
$userName = $userDir.Name
# Получаем имя Архива
$archiveName = Join-Path -Path $backupPath -ChildPath "$userName.rar"
Write-Host "Архивирую $userDir" -ForegroundColor Green -NoNewline
# Список аргментов для WinRar
$exclusions = Join-Path -Path $PSScriptRoot -ChildPath "exclusions.lst"
$arguments = "a", "-r", "-x@$exclusions","-ep1", $archiveName, "$userDir"
Start-Process -FilePath $winrarPath -ArgumentList $arguments -NoNewWindow -Wait
Write-Host " - готово"
# Удаляем пользователя, если архивирование прошло успешно
if (Test-Path $archiveName) {
Write-Host "Удаляю дирректорию $userDir" -NoNewline -ForegroundColor Red
# Встроенный Remove-Item иногда не мог удалить, потому используем rd
cmd.exe /c rd /s /q "$userDir"
Write-Host " - готово"
# Удаляем ветку пользователя из реестра
try {
# Получаем объект пользователя и его SID
$user = New-Object System.Security.Principal.NTAccount($userName)
$userSID = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value
# Путь к ветке ProfileList в реестре
$registryPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$userSID"
# Проверяем, существует ли указанная ветка
if (Test-Path $registryPath) {
try {
# Удаляем ветку
Remove-Item -Path $registryPath -Recurse -Force
Write-Host "Ветка пользователя $userName (SID: $userSID) успешно удалена из реестра."
}
catch {
Write-Host "Ошибка при удалении ветки: $registryPath"
}
}
else {
Write-Host "Ветка пользователя $userName (SID: $userSID) не найдена в реестре."
}
}
catch {
Write-Host "Ошибка: Не удалось найти пользователя $userName или получить его SID."
}
}
Write-Host ""
}
*\3D Objects\
*\AppData\
*\Application Data\
*\Contacts\
*\Cookies\
*\Favorites\
*\IntelGraphicsProfiles\
*\Links\
*\Local Settings\
*\NetHood\
*\OneDrive\
*\PrintHood\
*\Recent\
*\Saved Games\
*\Searches\
*\SendTo\
*\StartupDis\
*\Videos\
*\главное меню\
*\Мои документы\
*\Шаблоны\
*\WINDOWS\
desktop.ini
*.bin
*NTUSER*
~*
*.tmp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment