Администраторы время от времени должны удалять старые профили пользователей (уволенные пользователи, неактивные пользователи, и т.д.) в каталоге C:\Users на рабочих станциях и серверах Windows. Чаще всего с задачей очисткой профилей пользователей Windows сталкиваются на терминальных серверах RDS (Remote Desktop Services).
Основная проблема терминальных серверов – постоянный рост размеров каталогов профилей пользователей на диске. Частично эта проблема решается политиками квотирования размера профиля пользователя с помощью FSRM или NTFS квот, использованием профилей типа FSLogix или User Profile Disk, перемещаемыми папками и т.д. Но при большом количестве RDS пользователей в папке C:\Users со временем накапливается огромное количество каталогов с неиспользуемыми профилями пользователей.
Содержание:
- Как вручную удалить профиль пользователя в Windows?
- Групповая политика для автоматической очистки старых профилей
- PowerShell скрипт для удаления старых профилей пользователей в Windows
Как вручную удалить профиль пользователя в Windows?
В Windows вы можете вручную удалить профиль пользователя через панель управления.
- Откройте Advanced System Settings (команда
SystemPropertiesAdvanced
) -> User Profiles -> Settings; - В этом окне перечислен список всех профилей пользователей (локальных и доменных), которые хранятся на этом компьютере. Размер каждого профиля пользователя на диске указан в столбце Size.
- Выберите пользователя, чей профиль нужно удалить и нажмите кнопку Delete.
В Windows 11/10 и Windows Server 2022/2019 вы можете удалить профили пользователей с диска через приложение Settings. Перейдите в раздел Accounts -> Access work and school (или выполните команду быстрого доступа
ms-settings:otherusers
). Выберите пользователя и нажмите Remove чтобы удалить его данные с компьютера.
При корректном удалении профиля пользователя с диска будет удален каталог профиля в C:\Users и запись о пользователе в реестре.
Многие начинающиеся администраторы пытаются вручную удалить каталог с профилем пользователя из папки C:\Users. В этом случае нужно обязательно вручную удалить информацию о профиле из реестра Windows:
- Откройте редактор реестра
regedit.exe
; - Перейдите в ветку HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
- Для каждого пользователя, выполнившего локальный вход в систему (этот метод входа должен быть разрешен пользователю настройками параметра Allow log on locally в GPO), создается отдельная ветка с SID пользователя в качестве имени;
- Вы можете найти раздел реестра, соответствующий пользователю по SID, или можете вручную просмотреть содержимое всех вложенных разделв, пока не найдете раздел, в котором значение ProfileImagePath указывает на каталог с профилем пользователя на диске (например,
C:\Users\kbuldogov
); - Удалите данный раздел реестра, чтобы завершить корректное удаление профиля.
Также вы можете удалить профиль конкретного пользователя с помощью PowerShell:
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split(‘\’)[-1] -eq 'kbuldogov' } | Remove-CimInstance
Эта команда удалит как каталог на диске, так и ссылку на профиль пользователя kbuldogov в реестре HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.
Эта команда будет работать как в Windows PowerShell, так и в новых версиях PowerShell Core 6.x,7.x
Можно удалить профиль пользователя на удаленном компьютере с помощью PowerShell Remoting и командлета Invoke-Command:
$compname="wks21s32"
$user = "kbuldogov"
Invoke-Command -ComputerName $compname -ScriptBlock {
param($user)
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split(‘\’)[-1] -eq $user } | Remove-CimInstance
} -ArgumentList $user
Групповая политика для автоматической очистки старых профилей
В Windows есть специальный параметр групповой политики для автоматического удаления старых профилей пользователей старше xx дней. Вы можете включить этот параметр с помощью локального редактора GPO (
gpedit.msc
) или с помощью консоли управления доменными GPO (
gpmc.msc
). В этом примере на назначим политику автоматической очистки профилей на хосты в ферме RDS, которые вынесены в отдельный контейнер (Organizational Unit) Active Directory.
Прежде чем применять политику удаления старых профилей ко всем хостам, настоятельно рекомендуем проверить ее на тестовом сервере. Выведите один из серверов RDSH в режим обслуживания и протестируйте политику на нем.
- Найдите OU с компьютерами/серверами, на который вы хотите применить политику очистки старых профилей пользователей. Щелкните по OU и выберите Create a GPO in this domain and Link it here;
- Укажите имя политики и отредактируйте GPO;
- Перейдите в раздел Конфигурация компьютера -> Административные шаблоны -> Система -> Профили пользователей (Computer Configuration -> Administrative Templates -> System -> User Profiles);
- Откройте параметр “Удалять при перезагрузке системы профили пользователей по истечении указанного числа дней” (Delete user profiles older than a specified number days on system restart);
- Включите политику и укажите через сколько дней профиль пользователя считается неактивным и “Служба профилей пользователей Windows” можно автоматически удалить такой профиль при следующей перезагрузке. Обычно тут стоит указать не менее 45-90 дней;
- После применения новых настроек групповых политк, служба User Profile Services на ваших серверах Windows будет автоматически удалять старые профили пользователей. Удаление выполняется при перезагрузке сервера.
При использовании этой политики нужно быть уверенным, что при выключении/перезагрузке сервера нет проблем с системным временем (время не сбивается), иначе могут быть удалены профили активных пользователей.
Другой недостаток — вы не можете запретить удаление определенных профилей, например, локальных учетных записей, администраторов и т.д.
В версиях до Windows 11/10 и Windows Server 2022/2019 эта политика работала некорректно. Дело в том, что неактивноть профиля пользователя ранее определялась по дате именения файла NTUSER.dat. При установке обновлений Windows, служба Trusted Installer может менять дату изменения файла NTUSER.dat в профиле каждого пользователя. В результате служба Win32_UserProfile считает, что профиль использовался недавно.
В современных версиях Windows эта политика проверяет активность профиля пользователей по параметрам LocalProfileUnloadTimeLow и LocalProfileUnloadTimeHigh в ветке
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\<User Sid>
.
Вы можете получить значения параметров реестра LocalProfileLoadTimeLow и LocalProfileUnloadTimeHigh в привычном формате времени с помощью скрипта:
$profilelist = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" foreach ($p in $profilelist) { try { $objUser = (New-Object System.Security.Principal.SecurityIdentifier($p.PSChildName)).Translate([System.Security.Principal.NTAccount]).value } catch { $objUser = "[UNKNOWN]" } Remove-Variable -Force LTH,LTL,UTH,UTL -ErrorAction SilentlyContinue $LTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeHigh -ErrorAction SilentlyContinue).LocalProfileLoadTimeHigh $LTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileLoadTimeLow -ErrorAction SilentlyContinue).LocalProfileLoadTimeLow $UTH = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeHigh -ErrorAction SilentlyContinue).LocalProfileUnloadTimeHigh $UTL = '{0:X8}' -f (Get-ItemProperty -Path $p.PSPath -Name LocalProfileUnloadTimeLow -ErrorAction SilentlyContinue).LocalProfileUnloadTimeLow $LoadTime = if ($LTH -and $LTL) { [datetime]::FromFileTime("0x$LTH$LTL") } else { $null } $UnloadTime = if ($UTH -and $UTL) { [datetime]::FromFileTime("0x$UTH$UTL") } else { $null } [pscustomobject][ordered]@{ User = $objUser SID = $p.PSChildName Loadtime = $LoadTime UnloadTime = $UnloadTime } }
PowerShell скрипт для удаления старых профилей пользователей в Windows
Вы можете удалять профили неактивных или заблокированных пользователей с помощью скрипта PowerShell.
Сначала попробуем подсчитать размер профиля каждого пользователя в папке C:\Users c помощью простого скрипта из статьи “Вывести размер папок с помощью PowerShell”:
gci -force ‘C:\Users\’-ErrorAction SilentlyContinue | Where { !($_.Attributes -match " ReparsePoint") }| ? { $_ -is [io.directoryinfo] } | % {
$len = 0
gci -recurse -force $_.fullname -ErrorAction SilentlyContinue | % { $len += $_.length }
$_.fullname, ‘{0:N2} GB’ -f ($len / 1Gb)
$sum = $sum + $len
}
“Общий размер профилей”,'{0:N2} GB’ -f ($sum / 1Gb)
Итого суммарный размер всех профилей пользователей в каталоге C:\Users около 22 Гб.
Теперь выведем список пользователей, профиль которых не использовался более 60 дней. Для поиска можно использовать значение атрибута профиля LastUseTime.
Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-60))}| Measure-Object
У меня на терминальном сервере оказалось 143 профиля неактивных пользователей (общим размером около 10 Гб).
Следующий PowerShell скрипт выведет список подробную информацию о профилях пользователей, которые не обновлялись более 60 дней. Скрипт сконвертирует SID пользователя в имя, посчитает размер профиля каждого пользователя и выведет все в таблице:
$allprofilesinfo = @() $OldProfiles=Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-60))} Foreach ($OldProfile in $OldProfiles) {$objSID = New-Object System.Security.Principal.SecurityIdentifier ($OldProfile.SID) $objUser = $objSID.Translate( [System.Security.Principal.NTAccount]) $userinfo = New-Object PSObject -Property @{ userName = $objUser.Value ProfilePath = $OldProfile.localpath LastUsedDate = $OldProfile.ConvertToDateTime($OldProfile.LastUseTime) FolderSize = "{0:N2} GB" -f ((gci –force $OldProfile.localpath –Recurse -ErrorAction SilentlyContinue| measure Length -s).sum / 1Gb) } $allprofilesinfo += $userinfo } $allprofilesinfo
Чтобы удалить все эти профили достаточно добавить перенаправить список на команду Remove-WmiObject (перед использование скрипта удаления желательно несколько раз перепроверить его вывод с помощью параметра –WhatIf ):
Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and (!$_.Loaded) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-30))} | Remove-WmiObject –WhatIf
Как мы уже упомянули выше, при установке некоторых обновлений Windows, служба Trusted installer может менять дату изменения файла NTUSER.dat в профиле каждого пользователя.
На скриншоте выше видно, что все профили были изменены примерно в одно и тоже время. Проверьте дату последней установки обновлений в Windows:
gwmi win32_quickfixengineering |sort installedon |select InstalledOn -Last 1
Или с помощью модуля PSWindowsUpdate:
Get-WUHistory | Select-Object -First 20
Скорее всего она совпадет с датой изменения профилей. Поэтому в старых версиях Windows можно получить список неактивных профилей с помощью другого скрипта, который проверяет атрибуту lastwritetime каталога пользователя:
$USERS= (Get-ChildItem -directory -force 'C:\Users' | Where { ((Get-Date) — $_.lastwritetime).days -ge 60 } | % {'c:\users\' + $_.Name})
foreach ($User in $USERS) {
Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and (!$_.Loaded) -and ($_.LocalPath -eq $User)} | Remove-WmiObject WhatIf }
Чтобы не удалять профили некоторых пользователей, например, специальные аккаунты System и Network Service, учетную запись локального администратора, пользователей с активными сессиями, список аккаунтов-исключений), нужно модифицировать скрипт следующим образом:
#Список аккаунтов, чьи профили нельзя удалять
$ExcludedUsers ="Public","zenoss","svc",”user_1”,”user_2”
$LocalProfiles=Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and (!$_.Loaded) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-60))}
foreach ($LocalProfile in $LocalProfiles)
{
if (!($ExcludedUsers -like $LocalProfile.LocalPath.Replace("C:\Users\","")))
{
$LocalProfile | Remove-WmiObject
Write-host $LocalProfile.LocalPath, "профиль удален” -ForegroundColor Magenta
}
}
Вы можете настроить запуск этого скрипта через shutdown скрипт групповой политики или по расписанию заданием планировщика. (перед настройкой автоматического удаления профилей внимательно протестируйте скрипт в своей среде!).
Можно модифицировать скрипт, чтобы автоматически удалять пользователи всех пользователей, которые добавлены в определенную группу AD. Например, вы хотите автоматически удалять профили уволившихся пользователей. Просто добавьте такие учетные записи в группу DisabledUsers и выполните на сервере скрипт:
$users = Get-ADGroupMember -Identity DisabledUsers | Foreach {$_.Sid.Value}
$profiles = Get-WmiObject Win32_UserProfile
$profiles | Where {$users -eq $_.Sid} | Foreach {$_.Delete()}
A common pain point in an IT administrator’s career is user profiles. User profiles are a ubiquitous part of a Windows IT pro’s life; especially those that manage virtual desktop environments like Remote Desktop Services (RDS) or Citrix. In this post, I’m going to demonstrate a way you take out your aggression by using PowerShell to delete user profiles (and discover them).
Windows system administrators have to deal with:
- corrupted user registry hives
- files that need shared across all user profiles
- figuring out how to recreate corrupt profiles
- …and more
What was once a frustrating experience has gotten a little less frustrating with PowerShell. Here are a few ways that PowerShell can make managing Windows user profiles easier.
Enumerating User Profiles
It’s easy to take a peek at user profiles on the file system on a single Windows computer. Simply look in the C:\Users folder. But not only are you not getting the full picture when you do this, it’s also troublesome due to potential file system access problems. There’s a better way and that’s through WMI or CIM. In CIM, a class exists called Win32_UserProfile. This class contains all of the profiles that exist on a machine and lots of other useful information that a simple file system folder won’t tell you.
Using PowerShell, you can access this CIM class with the Get-CimInstance
command.
Below, I’m finding the first user profile on the the local computer. You’ll notice many useful tidbits of information like LastUseTime
, SID
and so on.
PS C:\> Get-CimInstance -ClassName win32_userprofile | Select-Object -First 1
AppDataRoaming : Win32_FolderRedirectionHealth
Contacts : Win32_FolderRedirectionHealth
Desktop : Win32_FolderRedirectionHealth
Documents : Win32_FolderRedirectionHealth
Downloads : Win32_FolderRedirectionHealth
Favorites : Win32_FolderRedirectionHealth
HealthStatus : 3
LastAttemptedProfileDownloadTime :
LastAttemptedProfileUploadTime :
LastBackgroundRegistryUploadTime :
LastDownloadTime :
LastUploadTime :
LastUseTime : 3/14/2019 3:06:39 PM
Links : Win32_FolderRedirectionHealth
Loaded : False
LocalPath : C:\Users\.NET v4.5 Classic
Music : Win32_FolderRedirectionHealth
Pictures : Win32_FolderRedirectionHealth
RefCount :
RoamingConfigured : False
RoamingPath :
RoamingPreference :
SavedGames : Win32_FolderRedirectionHealth
Searches : Win32_FolderRedirectionHealth
SID : S-1-5-82-3876422241-1344743610-1729199087-774402673-2621913236
Special : False
StartMenu : Win32_FolderRedirectionHealth
Status : 0
Videos : Win32_FolderRedirectionHealth
PSComputerName :
The Get-CimInstance
cmdlet not only works locally but remotely as well. By using the ComputerName
parameter, you can specify, 1, 10 or 100 different remote computers and it will happily query each one.
PS C:\> Get-CimInstance -ClassName Win32_UserProfile -ComputerName localhost,WINSRV
Deleting User Profiles
Once you understand how to enumerate user profiles on computers, you can take it one step further and delete those user profiles as well.
I can’t count how many times I’ve had to delete user profiles because something got corrupted and I just needed the user to log in again and recreate it. At one time, I would simply have the user log off and remove the C:\Users<UserName> folder from the file system. Usually it works, sometimes it didn’t. What I didn’t realize was that I was actually leaving some remnants behind.
The proper way to do this is to initiate a removal via CIM.
Using the same CIM class you just went over, it’s possible to not only just view profiles but you can completely remove them as well. This is the same as going into the User Profiles box under System settings and hitting the Delete button.
To do this, enumerate the user profiles again and this time apply a filter to pick a single user profile to remove. In this case, remove the user profile called UserA. You can do this by using PowerShell’s Where-Object
cmdlet and some string manipulation to grab the user folder name from the LocalPath
property as shown below.
Once you’re able to narrow down that single profile you can pass that CIM instance to the Remove-CimInstance
cmdlet for each object that Get-CimInstance
returns. This process will remove the user profile from the file system and the registry.
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq 'UserA' } | Remove-CimInstance
Again, if you’d like to extend this to multiple computers you’d simply use the ComputerName
parameter on Get-CimInstance
.
Get-CimInstance -ComputerName SRV1,SRV2,SRV3 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq 'UserA' } | Remove-CimInstance
Manage and Report Active Directory, Exchange and Microsoft 365 with ManageEngine ADManager Plus. Download Free Trial!
Summary
You’ve now seen an easy way to enumerate and delete Windows user profiles. If you weren’t aware of the CIM class Win32_UserProfile you may have been correlating the C:\Users<Username> folder as the profile but you should know to delete the Win32_UserProfile CIM instance now.
You can see there’s much more to the user profile than a simple file system folder. Use CIM the next time you need to query or delete user profiles from Windows computers in your environment.
To remove a user profile in PowerShell, you can use the `Remove-WmiObject` cmdlet along with the appropriate filter for the user profile you want to delete. Here’s how to do it:
Get-WmiObject -Class Win32_UserProfile | Where-Object { $_.LocalPath -like "*USERNAME*" } | Remove-WmiObject
Replace `USERNAME` with the actual username of the profile you wish to remove.
Understanding User Profiles
What is a User Profile?
A user profile in Windows is a collection of personalized settings that define how a user interacts with their environment. It includes desktop settings, user files, application data, and preferences. Each user who logs onto a Windows machine has a unique user profile, allowing for a tailored experience.
Why Remove a User Profile?
Several situations necessitate the removal of a user profile:
- Inactive or unused profiles: These can consume system resources unnecessarily.
- Corrupted profiles: Corrupted user profiles may lead to errors and operational challenges.
- User departure: When an employee leaves an organization, their profile should often be deleted for security and privacy reasons.
Mastering the PowerShell UserProfile: A Quick Guide
PowerShell Basics
Introduction to PowerShell
PowerShell is an interactive command-line shell and scripting language designed for system administration. It provides powerful tools to automate tasks and manage configurations. Mastering PowerShell is essential for IT professionals who deal with systems and infrastructure.
Safety Precautions Before Deleting a Profile
Before executing any commands to remove user profiles, it is crucial to consider the following safety precautions:
- Back up user data: Always ensure that important data associated with the user profile is backed up. Files can often be critical, and their loss may have serious repercussions.
- Check for active processes: Users might have applications open that are associated with their profile. This precaution will help avoid complications during the removal process.
PowerShell Reload Profile: A Quick Guide to Refreshing Settings
PowerShell Commands for User Profile Management
Using the Get-WmiObject Cmdlet
To manage user profiles effectively, the first step often involves viewing the active profiles on a system. The `Get-WmiObject` cmdlet is instrumental for this purpose:
Get-WmiObject Win32_UserProfile
This command returns a list of user profiles, including their unique identifiers, local paths, and the last time they were used. This information is fundamental for identifying profiles that may need removal.
Identifying Profiles to Remove
When you’ve retrieved the list of profiles, filtering is crucial. For example, to identify profiles that haven’t been used in over 30 days, you can use:
$thresholdDate = (Get-Date).AddDays(-30)
Get-WmiObject Win32_UserProfile | Where-Object { $_.LastUseTime -lt $thresholdDate }
This command allows you to home in on profiles that are candidates for deletion.
Removing User Profiles with PowerShell
Delete User Profile using Remove-WmiObject
Once you’ve identified the user profiles that need to be removed, the next step is the actual deletion. Using `Remove-WmiObject` offers a straightforward way to remove a specified user profile.
Here’s an example to delete a specific user profile named «UserProfileName»:
$profile = Get-WmiObject Win32_UserProfile | Where-Object { $_.LocalPath -like "*UserProfileName*" }
Remove-WmiObject -InputObject $profile
In this command:
- The first line gathers the specific profile, filtering by the local path.
- The second line executes the deletion.
Using the Remove-CimInstance Cmdlet
An alternative to `Remove-WmiObject` is the `Remove-CimInstance` cmdlet. This command offers a more efficient approach in some scenarios.
Here’s how to delete a user profile with this cmdlet:
$profile = Get-CimInstance Win32_UserProfile | Where-Object { $_.LocalPath -like "*UserProfileName*" }
Remove-CimInstance -InputObject $profile
The benefit of this method is that `CIM` (Common Information Model) provides a simplified and potentially faster interaction with WMI.
Mastering PowerShell Noprofile for Swift Command Execution
Script Automation
Creating a PowerShell Script to Batch Delete Profiles
If you’re faced with numerous profiles to delete, a script can automate the process, saving time and effort. The following example script removes profiles that haven’t been used in over 30 days:
$thresholdDate = (Get-Date).AddDays(-30)
Get-WmiObject Win32_UserProfile | Where-Object { $_.LastUseTime -lt $thresholdDate } | ForEach-Object { Remove-WmiObject -InputObject $_ }
In this script:
- The `$thresholdDate` variable sets the last access date cutoff.
- The `Get-WmiObject` command retrieves all profiles, filtering for last use time.
- The `ForEach-Object` processes each filtered profile, removing it.
PowerShell Remove Printer: A Quick Guide to Cleanup
Verifying User Profile Removal
Confirming Successful Deletion of Profiles
After you’ve executed the removal, it’s essential to verify that the profile was deleted successfully. You can do this by running:
Get-WmiObject Win32_UserProfile
If the profile no longer appears in the list, the removal was successful.
Troubleshooting Common Errors and Responses
Occasionally, you may encounter errors during the deletion process. Common issues include:
- Insufficient permissions: Ensure you are running PowerShell as an administrator.
- Active processes: If a user is logged in or applications are using the profile, Windows might not allow you to delete it.
PowerShell Remove Defender: Quick Command Guide
Conclusion
Efficient PowerShell remove user profile processes are crucial in managing Windows environments. Regularly auditing user profiles can help maintain an optimal system performance and enhance security by ensuring that unused profiles do not linger.
Always remember to back up data before any deletions and check for active users or programs that may be impacted by the removal. With these practices, using PowerShell to manage user profiles can significantly simplify administrative tasks.
Mastering the PowerShell Profiler for Efficient Scripting
Frequently Asked Questions
What happens if I delete a user profile in Windows?
When a user profile is deleted, all associated files, settings, and configurations are removed. If the profile is tied to an existing user account, that account may revert to a default state until a new profile is created.
Can I recover a deleted user profile?
Recovering a deleted user profile can be challenging, especially if no backups are available. Without restoration points or backups, the data in the profile is typically unrecoverable.
Is it safe to delete local user profiles?
Yes, it’s safe to delete local profiles provided you’ve ensured the data is backed up and the user no longer needs access to that environment. Always double-check that important files have been preserved before proceeding with deletions.
One of my clients recently wanted us to delete old and unused user profiles from Windows 11 as they took up valuable disk space. You can manage user profiles using PowerShell. In this tutorial, I will explain how to delete user profiles using PowerShell in Windows 11.
Note: Ensure you have administrative access to the Windows 11 machine.
Method 1: Using the System Settings
The simplest way to delete a user profile in Windows 11 is through the System Settings. Here’s how:
- Click on the Start menu and select the Settings app.
- Navigate to “System” and then click on “Storage.”
- Under “Storage management,” click on “User Profiles.”
- Select the profile you wish to delete and click on “Delete.”
However, keep in mind that this method may not always work, especially if the user profile is corrupted or locked. In such cases, you can use PowerShell.
Check out Generate SSH Keys with PowerShell
Method 2: Using PowerShell
Now, let me show you how to use PowerShell to delete user profiles in Windows 11. Follow these steps:
- Open the Start menu, type “PowerShell,” right-click on “Windows PowerShell,” and select “Run as administrator.”
- In the PowerShell window, type the following command and press Enter:
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq 'USERNAME' } | Remove-CimInstance
Replace ‘USERNAME’ with the actual username of the profile you want to delete. For example, if the username is ‘Bijay,’ the command would be:
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq 'Bijay' } | Remove-CimInstance
This command uses the CIM (Common Information Model) cmdlets to retrieve the user profile information and delete the specified profile.
- If the user profile is currently loaded, you may encounter an error. In such cases, you can force the deletion by adding the
-Force
parameter:
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq 'USERNAME' } | Remove-CimInstance -Force
Be cautious when using the -Force
parameter, as it will delete the user profile without any prompts or confirmation.
Check out Show Logged-In Users with PowerShell
Method 3: Using a PowerShell Script
Sometimes, you might need to perform bulk operations, such as deleting multiple user profiles in Windows 11 with a PowerShell script.
Here’s an example script that deletes user profiles based on a specific condition:
$UserProfiles = Get-CimInstance -Class Win32_UserProfile
$DaysOld = 90
foreach ($UserProfile in $UserProfiles) {
$LastUsed = $UserProfile.LastUseTime
if ($LastUsed -lt (Get-Date).AddDays(-$DaysOld)) {
$UserProfile | Remove-CimInstance
Write-Host "Deleted user profile: $($UserProfile.LocalPath)"
}
}
This script does the following:
- It retrieves all user profiles using the
Get-CimInstance
cmdlet. - It defines a variable
$DaysOld
to specify the number of days (in this case, 90) after which a user profile should be considered old and eligible for deletion. - It iterates through each user profile and checks the
LastUseTime
property. - If the
LastUseTime
is older than the specified number of days ($DaysOld
), the script deletes the user profile using theRemove-CimInstance
cmdlet and displays a message indicating the deleted profile.
You can save this script with a .ps1
extension (e.g., DeleteOldProfiles.ps1
) and run it in PowerShell with administrative privileges.
Conclusion
In this tutorial, I explained how to delete user profiles in Windows 11 using PowerShell. This will help you manage your system’s storage and performance. Do let me know in the comments below if you face any issues.
You may also like:
- How to Remove a Computer from a Domain Using PowerShell
- Add a Computer to a Domain Using PowerShell
- Set the Default Printer Using PowerShell in Windows
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.
Привет. Сегодня хочу показать очередной скрипт PowerShell. В этот раз будем удалять профили пользователей в Windows. При этом удаляться будут все профили, которые есть на сервере разом, за исключением указанных нами.
Скачать скрипт.
Проект на github.
Сразу покажу вам текст скрипта:
Function Set-Owner {
<#
.SYNOPSIS
Changes owner of a file or folder to another user or group.
.DESCRIPTION
Changes owner of a file or folder to another user or group.
.PARAMETER Path
The folder or file that will have the owner changed.
.PARAMETER Account
Optional parameter to change owner of a file or folder to specified account.
Default value is 'Builtin\Administrators'
.PARAMETER Recurse
Recursively set ownership on subfolders and files beneath given folder.
.NOTES
Name: Set-Owner
Author: Boe Prox
Version History:
1.0 - Boe Prox
- Initial Version
.EXAMPLE
Set-Owner -Path C:\temp\test.txt
Description
-----------
Changes the owner of test.txt to Builtin\Administrators
.EXAMPLE
Set-Owner -Path C:\temp\test.txt -Account 'Domain\bprox
Description
-----------
Changes the owner of test.txt to Domain\bprox
.EXAMPLE
Set-Owner -Path C:\temp -Recurse
Description
-----------
Changes the owner of all files and folders under C:\Temp to Builtin\Administrators
.EXAMPLE
Get-ChildItem C:\Temp | Set-Owner -Recurse -Account 'Domain\bprox'
Description
-----------
Changes the owner of all files and folders under C:\Temp to Domain\bprox
#>
[cmdletbinding(
SupportsShouldProcess = $True
)]
Param (
[parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[Alias('FullName')]
[string[]]$Path,
[parameter()]
[string]$Account = 'Builtin\Administrators',
[parameter()]
[switch]$Recurse
)
Begin {
#Prevent Confirmation on each Write-Debug command when using -Debug
If ($PSBoundParameters['Debug']) {
$DebugPreference = 'Continue'
}
Try {
[void][TokenAdjuster]
} Catch {
$AdjustTokenPrivileges = @"
using System;
using System.Runtime.InteropServices;
public class TokenAdjuster
{
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("kernel32.dll", ExactSpelling = true)]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr
phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name,
ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static bool AddPrivilege(string privilege)
{
try
{
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
catch (Exception ex)
{
throw ex;
}
}
public static bool RemovePrivilege(string privilege)
{
try
{
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = GetCurrentProcess();
IntPtr htok = IntPtr.Zero;
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_DISABLED;
retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
return retVal;
}
catch (Exception ex)
{
throw ex;
}
}
}
"@
Add-Type $AdjustTokenPrivileges
}
#Activate necessary admin privileges to make changes without NTFS perms
[void][TokenAdjuster]::AddPrivilege("SeRestorePrivilege") #Necessary to set Owner Permissions
[void][TokenAdjuster]::AddPrivilege("SeBackupPrivilege") #Necessary to bypass Traverse Checking
[void][TokenAdjuster]::AddPrivilege("SeTakeOwnershipPrivilege") #Necessary to override FilePermissions
}
Process {
ForEach ($Item in $Path) {
Write-Verbose "FullName: $Item"
#The ACL objects do not like being used more than once, so re-create them on the Process block
$DirOwner = New-Object System.Security.AccessControl.DirectorySecurity
$DirOwner.SetOwner([System.Security.Principal.NTAccount]$Account)
$FileOwner = New-Object System.Security.AccessControl.FileSecurity
$FileOwner.SetOwner([System.Security.Principal.NTAccount]$Account)
$DirAdminAcl = New-Object System.Security.AccessControl.DirectorySecurity
$FileAdminAcl = New-Object System.Security.AccessControl.DirectorySecurity
$AdminACL = New-Object System.Security.AccessControl.FileSystemAccessRule('Builtin\Administrators','FullControl','ContainerInherit,ObjectInherit','InheritOnly','Allow')
$FileAdminAcl.AddAccessRule($AdminACL)
$DirAdminAcl.AddAccessRule($AdminACL)
Try {
$Item = Get-Item -LiteralPath $Item -Force -ErrorAction Stop
If (-NOT $Item.PSIsContainer) {
If ($PSCmdlet.ShouldProcess($Item, 'Set File Owner')) {
Try {
$Item.SetAccessControl($FileOwner)
} Catch {
Write-Warning "Couldn't take ownership of $($Item.FullName)! Taking FullControl of $($Item.Directory.FullName)"
$Item.Directory.SetAccessControl($FileAdminAcl)
$Item.SetAccessControl($FileOwner)
}
}
} Else {
If ($PSCmdlet.ShouldProcess($Item, 'Set Directory Owner')) {
Try {
$Item.SetAccessControl($DirOwner)
} Catch {
Write-Warning "Couldn't take ownership of $($Item.FullName)! Taking FullControl of $($Item.Parent.FullName)"
$Item.Parent.SetAccessControl($DirAdminAcl)
$Item.SetAccessControl($DirOwner)
}
}
If ($Recurse) {
[void]$PSBoundParameters.Remove('Path')
Get-ChildItem $Item -Force | Set-Owner @PSBoundParameters
}
}
} Catch {
Write-Warning "$($Item): $($_.Exception.Message)"
}
}
}
End {
#Remove priviledges that had been granted
[void][TokenAdjuster]::RemovePrivilege("SeRestorePrivilege")
[void][TokenAdjuster]::RemovePrivilege("SeBackupPrivilege")
[void][TokenAdjuster]::RemovePrivilege("SeTakeOwnershipPrivilege")
}
}
function Get-UserSession {
<#
.SYNOPSIS
Retrieves all user sessions from local or remote computers(s)
.DESCRIPTION
Retrieves all user sessions from local or remote computer(s).
Note: Requires query.exe in order to run
Note: This works against Windows Vista and later systems provided the following registry value is in place
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\AllowRemoteRPC = 1
Note: If query.exe takes longer than 15 seconds to return, an error is thrown and the next computername is processed. Suppress this with -erroraction silentlycontinue
Note: If $sessions is empty, we return a warning saying no users. Suppress this with -warningaction silentlycontinue
.PARAMETER computername
Name of computer(s) to run session query against
.parameter parseIdleTime
Parse idle time into a timespan object
.parameter timeout
Seconds to wait before ending query.exe process. Helpful in situations where query.exe hangs due to the state of the remote system.
.FUNCTIONALITY
Computers
.EXAMPLE
Get-usersession -computername "server1"
Query all current user sessions on 'server1'
.EXAMPLE
Get-UserSession -computername $servers -parseIdleTime | ?{$_.idletime -gt [timespan]"1:00"} | ft -AutoSize
Query all servers in the array $servers, parse idle time, check for idle time greater than 1 hour.
.NOTES
Thanks to Boe Prox for the ideas - http://learn-powershell.net/2010/11/01/quick-hit-find-currently-logged-on-users/
.LINK
http://gallery.technet.microsoft.com/Get-UserSessions-Parse-b4c97837
#>
[cmdletbinding()]
Param(
[Parameter(
Position = 0,
ValueFromPipeline = $True)]
[string[]]$ComputerName = "localhost",
[switch]$ParseIdleTime,
[validaterange(0,120)]
[int]$Timeout = 15
)
Process
{
ForEach($computer in $ComputerName)
{
#start query.exe using .net and cmd /c. We do this to avoid cases where query.exe hangs
#build temp file to store results. Loop until we see the file
Try
{
$Started = Get-Date
$tempFile = [System.IO.Path]::GetTempFileName()
Do{
start-sleep -Milliseconds 300
if( ((Get-Date) - $Started).totalseconds -gt 10)
{
Throw "Timed out waiting for temp file '$TempFile'"
}
}
Until(Test-Path -Path $tempfile)
}
Catch
{
Write-Error "Error for '$Computer': $_"
Continue
}
#Record date. Start process to run query in cmd. I use starttime independently of process starttime due to a few issues we ran into
$Started = Get-Date
$p = Start-Process -FilePath C:\windows\system32\cmd.exe -ArgumentList "/c query user /server:$computer > $tempfile" -WindowStyle hidden -passthru
#we can't read in info or else it will freeze. We cant run waitforexit until we read the standard output, or we run into issues...
#handle timeouts on our own by watching hasexited
$stopprocessing = $false
do
{
#check if process has exited
$hasExited = $p.HasExited
#check if there is still a record of the process
Try
{
$proc = Get-Process -id $p.id -ErrorAction stop
}
Catch
{
$proc = $null
}
#sleep a bit
start-sleep -seconds .5
#If we timed out and the process has not exited, kill the process
if( ( (Get-Date) - $Started ).totalseconds -gt $timeout -and -not $hasExited -and $proc)
{
$p.kill()
$stopprocessing = $true
Remove-Item $tempfile -force
Write-Error "$computer`: Query.exe took longer than $timeout seconds to execute"
}
}
until($hasexited -or $stopProcessing -or -not $proc)
if($stopprocessing)
{
Continue
}
#if we are still processing, read the output!
try
{
$sessions = Get-Content $tempfile -ErrorAction stop
Remove-Item $tempfile -force
}
catch
{
Write-Error "Could not process results for '$computer' in '$tempfile': $_"
continue
}
#handle no results
if($sessions){
1..($sessions.count - 1) | Foreach-Object {
#Start to build the custom object
$temp = "" | Select ComputerName, Username, SessionName, Id, State, IdleTime, LogonTime
$temp.ComputerName = $computer
#The output of query.exe is dynamic.
#strings should be 82 chars by default, but could reach higher depending on idle time.
#we use arrays to handle the latter.
if($sessions[$_].length -gt 5){
#if the length is normal, parse substrings
if($sessions[$_].length -le 82){
$temp.Username = $sessions[$_].Substring(1,22).trim()
$temp.SessionName = $sessions[$_].Substring(23,19).trim()
$temp.Id = $sessions[$_].Substring(42,4).trim()
$temp.State = $sessions[$_].Substring(46,8).trim()
$temp.IdleTime = $sessions[$_].Substring(54,11).trim()
$logonTimeLength = $sessions[$_].length - 65
try{
$temp.LogonTime = Get-Date $sessions[$_].Substring(65,$logonTimeLength).trim() -ErrorAction stop
}
catch{
#Cleaning up code, investigate reason behind this. Long way of saying $null....
$temp.LogonTime = $sessions[$_].Substring(65,$logonTimeLength).trim() | Out-Null
}
}
#Otherwise, create array and parse
else{
$array = $sessions[$_] -replace "\s+", " " -split " "
$temp.Username = $array[1]
#in some cases the array will be missing the session name. array indices change
if($array.count -lt 9){
$temp.SessionName = ""
$temp.Id = $array[2]
$temp.State = $array[3]
$temp.IdleTime = $array[4]
try
{
$temp.LogonTime = Get-Date $($array[5] + " " + $array[6] + " " + $array[7]) -ErrorAction stop
}
catch
{
$temp.LogonTime = ($array[5] + " " + $array[6] + " " + $array[7]).trim()
}
}
else{
$temp.SessionName = $array[2]
$temp.Id = $array[3]
$temp.State = $array[4]
$temp.IdleTime = $array[5]
try
{
$temp.LogonTime = Get-Date $($array[6] + " " + $array[7] + " " + $array[8]) -ErrorAction stop
}
catch
{
$temp.LogonTime = ($array[6] + " " + $array[7] + " " + $array[8]).trim()
}
}
}
#if specified, parse idle time to timespan
if($parseIdleTime){
$string = $temp.idletime
#quick function to handle minutes or hours:minutes
function Convert-ShortIdle {
param($string)
if($string -match "\:"){
[timespan]$string
}
else{
New-TimeSpan -Minutes $string
}
}
#to the left of + is days
if($string -match "\+"){
$days = New-TimeSpan -days ($string -split "\+")[0]
$hourMin = Convert-ShortIdle ($string -split "\+")[1]
$temp.idletime = $days + $hourMin
}
#. means less than a minute
elseif($string -like "." -or $string -like "none"){
$temp.idletime = [timespan]"0:00"
}
#hours and minutes
else{
$temp.idletime = Convert-ShortIdle $string
}
}
#Output the result
$temp
}
}
}
else
{
Write-Warning "'$computer': No sessions found"
}
}
}
}
$ErrorActionPreference='Continue'
$excludes = new-object 'System.Collections.Generic.List[string]'
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" -rec -ea SilentlyContinue | foreach {
$CK = (Get-ItemProperty -Path $_.PsPath)
if ($CK.ProfileImagePath -match "systemprofile" -or $CK.ProfileImagePath -match "LocalService" -or $CK.ProfileImagePath -match "NetworkService" -or $CK.ProfileImagePath -match "administrator" -or $CK.ProfileImagePath -match "администратор" -or $CK.ProfileImagePath -match "MSSQL" -or $CK.ProfileImagePath -match ".NET " -or $CK.ProfileImagePath -match "sanglyb") {
$a = $CK
$excludes.add(($a.PSPath -split '\\')[7])
}
}
$loggedOnUsers = Get-UserSession
$User = "$env:userdomain\$env:username"
$mass_length=$excludes.Count
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" -rec -ea SilentlyContinue | foreach {
$CurrentKey = (Get-ItemProperty -Path $_.PsPath)
$temp_uid=($CurrentKey.PSPath -split '\\')[7]
$test=1
for ($i=0; $i -le $mass_length-1; $i++ ) {if ($temp_uid -like $excludes[$i]) {$test=0}
}
if ($test -eq 1) {
$a = $CurrentKey
$pat = $CurrentKey.ProfileImagePath
$test1=1
foreach ($loggedOnUser in $loggedOnUsers){
if ($pat -like "*"+$loggedOnUser.Username -or $pat -match $loggedOnUser.username+"\."){
$test1=0
}
}
if ($test1 -eq 1){
if ($pat -ne $null) {
$pat
Set-Owner -Path $Pat -Account $user -Recurse -ErrorAction SilentlyContinue
cmd /c "rd /s /q $pat"
}
if ($a.PSPath -ne $null) {Remove-Item -Path $a.PSPath -Recurse}
}
}
}
Теперь немного разберем его, но перед тем, как разбирать скрипт, необходимо понять как вообще удаляются профили пользователей в винде.
Для правильного удаления профиля нужно сделать 3 вещи:
- Убедиться, что пользователь не залогинен в системе. Т.к. если пользователь окажется активен, при удалении его папки не удалятся некоторые файлы, и у пользователя будут проблемы с последующим входом в систему. Решиться проблемы после такого, скорее всего смогут, только после перезагрузки сервера.
- Необходимо найти ветку пользователя в реестре. Находятся пользовательские ветки по пути – HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
В этой ветке необходимо посмотреть, где находится папка пользователя.
- Нужно удалить пользовательскую ветку в реестре и пользовательскую папку.
Ни чего сложного =).
Итак, разберем немного скрипт. Я не стал изобретать велосипед, и решил использовать для скрипта две функции, найденные на просторах TechNet. Для просмотра залогиненых пользователей, и для задания владельца папок и файлов. Об этих функциях ни чего говорить не буду.
Думаю, логично, что мы не хотим удалять профили всех пользователей. Нужно оставлять администраторские, общие и всякие сервисные профили. За это отвечает следующий кусок скрипта:
$excludes = new-object 'System.Collections.Generic.List[string]'
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" -rec -ea SilentlyContinue | foreach {
$CK = (Get-ItemProperty -Path $_.PsPath)
if ($CK.ProfileImagePath -match "systemprofile" -or $CK.ProfileImagePath -match "LocalService" -or $CK.ProfileImagePath -match "NetworkService" -or $CK.ProfileImagePath -match "administrator" -or $CK.ProfileImagePath -match "администратор" -or $CK.ProfileImagePath -match "MSSQL" -or $CK.ProfileImagePath -match ".NET " -or $CK.ProfileImagePath -match "sanglyb") {
$a = $CK
$excludes.add(($a.PSPath -split '\\')[7])
}
}
Тут мы берем пользовательские ветки реестров, и исходя из путей до папок, через условия определяем исключения. Для определения исключений можно использовать часть имени.
Дальше мы получаем список вошедших в систему пользователей, а также определяем пользователя от имени которого запущен скрипт:
$loggedOnUsers = Get-UserSession
$User = "$env:userdomain\$env:username"
В следующем куске мы перебираем все профили пользователей из реестра и отсеиваем исключения:
$mass_length=$excludes.Count
Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\" -rec -ea SilentlyContinue | foreach {
$CurrentKey = (Get-ItemProperty -Path $_.PsPath)
$temp_uid=($CurrentKey.PSPath -split '\\')[7]
$test=1
for ($i=0; $i -le $mass_length-1; $i++ ) {if ($temp_uid -like $excludes[$i]) {$test=0}
}
if ($test -eq 1) {
$a = $CurrentKey
$pat = $CurrentKey.ProfileImagePath
Далее мы смотрим что бы владелец профиля, который сейчас на очереди удаления не был залогинен в системе:
$test1=1
foreach ($loggedOnUser in $loggedOnUsers){
if ($pat -like "*"+$loggedOnUser.Username -or $pat -match $loggedOnUser.username+"\."){
$test1=0
}
}
if ($test1 -eq 1){
И наконец, если существуют ветка и папка удаляем их, предварительно став владельцем папки.
if ($pat -ne $null) {
$pat
Set-Owner -Path $Pat -Account $user -Recurse -ErrorAction SilentlyContinue
cmd /c "rd /s /q $pat"
}
if ($a.PSPath -ne $null) {Remove-Item -Path $a.PSPath -Recurse}
}
}
}
Такой вот скрипт. Надеюсь, он окажется вам полезным.