If you perform a clean Windows 11 / 10 installation or set up a new user account, you will be asked to log in with a Microsoft account. However, users have reported on multiple occasions that they need to provide their Microsoft account credentials each time they attempt to log into their accounts.
We will show you 3 methods to block/prevent Windows from asking for your Microsoft account credentials. By using these methods, you can also block other users on your computer from being asked for Microsoft account credentials.
Note that disabling a Microsoft account is not the same as removing a Microsoft account. Nevertheless, we have also covered this topic near the end of this post.
Table of Contents
Disable/block Microsoft Account using Group Policy
You can block Windows from asking for your Microsoft account credentials when trying to look into your computer account using the Group Policy Editor. Here is how:
Note: If you are using a Home edition of Windows 10 or 11, learn how to enable gpedit.msc or move on to the next section to use an alternative method.
- Open the Group Policy Editor by typing in gpedit.msc in the Run dialog box.
- Navigate to the following location using the left pane:
Computer Configuration >> Windows Settings >> Security Settings >> Local Polices >> Security Options
- Now double-click the policy “Accounts: Block Microsoft accounts” in the right pane.
- From the popup, select either of the following options according to your preferences. When selected, click Apply and Ok.
- The policy is disabled: This option disables the policy, which is the default setting.
- Users can’t add Microsoft accounts: This option disables users on the system from adding a new Microsoft account, but they can still use the one already used to sign in. This is a preferred option for existing Microsoft users who don’t want to add additional Microsoft accounts.
- Users can’t add or log in with Microsoft accounts: This option completely blocks Microsoft account access from your system. You can’t even log in to the system using your existing Microsoft account. You can only create a local account.
- Now run the Command Prompt with administrative rights and paste the following cmdlet to implement the changes.
gpupdate /force
Now you can sign out or restart your computer and log back in, and Windows will not ask for your Microsoft account information. However, you may need to now create a local account.
Disable/block Microsoft Account using Windows Registry
You can also achieve the same using the Windows Registry Editor. You can adapt this method if you are a Windows Home user. here is how to do so:
Note: Misconfiguration of critical values in the system’s registry could be fatal for your operating system. Therefore, we insist that you create a system restore point before proceeding forward with the process.
- Open the Registry Editor by typing in regedit in Run.
- Now paste the following in the navigation bar at the top for quick navigation:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
- Right-click the System Key in the left pane, expand New from the context menu, and then click DWORD (32-bit) Value.
- Name the new DWORD “NoConnectedUser.”
- Double-click the newly-created DWORD and set its Value Data to either of the following values:
- 0 = Allow Microsoft Accounts
- 1 = Users can’t add Microsoft Accounts
- 3 = Users can’t add or log on with Microsoft accounts
Click OK when done.
- Now restart your computer for the changes to take effect.
The Value Data options you use for the “NoConnectedUser” Value are similar to the 3 options we saw in the Group Policy “Accounts: Block Microsoft accounts” we saw in the last section above.
Block from Switching to Microsoft Account from Registry
You can also implement this method to block local accounts from converting to Microsoft account using the Registry Editor.
- Open the Registry Editor by typing in regedit in Run.
- Now paste the following into the navigation bar at the top for quick navigation:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PolicyManager\default\Settings\AllowYourAccount
- Here, double-click on “Value” in the right pane and set its Value Data to 0. Then click Ok.
- Now reboot your PC for the changes to take effect.
When you return, you will see that the option to “Sign in with a Microsoft account instead” is greyed out on the Accounts Settings page.
These are the 3 methods that prevent Windows from asking for your Microsoft account credentials. Let us now show you how to simply remove a Microsoft account and convert it into a local account instead.
How to Remove Microsoft Account
Perform the following steps to remove the Microsoft account from your computer account:
- Navigate to the following:
Settings app >> Accounts >> Email and accounts
- Here, click on your Microsoft account to expand it:
- Now click Remove under your Microsoft account, and then click Yes from the confirmation box.
Your Microsoft account will now be removed from your PC.
Final Thoughts
Removing a Microsoft account from your computer account may save you the trouble of not having to put in your credentials. However, you may also lose a few Windows features this way, such as synced Clipboard, Cortana search, etc. You can no longer sync your settings and other data between devices, as the Microsoft account no longer exists on that PC.
If you have to enter your Microsoft account credentials each time while logging in, we suggest you set up a PIN to log in faster, while maintaining your Microsoft account on the PC.
Adding a new account in Windows 11 / Windows 10 creates a user profile, a collection of settings, and folders that ensure each person on the PC has a unique, customized experience. This also contains their documents, saved games, videos, and more. This can take up some space, but fortunately, Windows lets you delete a user profile if you no longer need it or it gets corrupted.
The Difference Between User Profiles and User Accounts in Windows
Managing user data and settings on Windows 10 and 11 systems involves understanding the distinction between a user account and a user profile. While often used interchangeably, these two components serve different yet complementary roles in the Windows operating environment.
A user account is essentially the gateway to accessing a Windows system, acting as the user’s identity for system access. It consists of a username and, optionally, a password, which are required to log into Windows. User accounts can be associated with different levels of privileges, such as standard user rights or administrative permissions, determining what the user can and cannot do on the system.
In contrast, a user profile is a personalized environment linked to a user account. Once a user logs in, the system loads a unique user profile containing personal settings, configurations, desktop backgrounds, application settings, and files stored in the user’s personal folders. This profile ensures that each user’s experience is tailored to their preferences and saved from session to session.
Deleting a Windows User Profile vs. Deleting a Windows User Account
Deleting a user profile is a process distinct from deleting a user account. When you delete a user profile in Windows 10 or 11, you’re removing all the personalized settings and files associated with that profile, effectively resetting the user’s environment to a default state. However, the user account itself may remain intact, allowing for the creation of a new profile when the user logs in again. This process can be essential for troubleshooting, such as when a profile becomes corrupted, or for removing the data of users who no longer need access to the system.
There are multiple methods to delete a user profile in Windows, each suitable for different scenarios and user preferences. The Settings app offers a straightforward approach for those seeking simplicity, while the Control Panel and User Accounts Wizard provide more granular control over the deletion process. For a comprehensive removal, especially to address deeper system-level issues or ensure the complete clearance of all profile remnants, Advanced System Properties might be the preferred method.
⚠️ Please note: The process described below is the same in Windows 11 as it is in Windows 10. However, bear in mind that we’ll be using screenshots from Windows 10, so your UI may look a little different. We’ll point out any changes you need to be aware of as they come up.
How to Delete a Windows User Profile via System Properties
Before you start this process, make sure the user account you wish to delete is signed out.
- Open System Properties
Press “Windows + R” to open the Run dialog, type “systempropertiesadvanced.exe”, and click “OK”.
- Open the Windows 11 / Windows 10 user profile settings
In the “Advanced” tab, look for the “User Profiles” heading and click “Settings…”.
- Delete the Windows 11 / Windows 10 user profile
Windows 11 / Windows 10 will now return a list of user profiles linked to certain accounts. You’ll be able to see the name of the account after the PC identifier. Click the account, then press “Delete”.
- Confirm the Windows 11 / Windows 10 delete user profile action
Microsoft will then make sure you really want to remove the user profile. You should make sure there are no files or settings you need on that account before you continue. When ready, click “Yes”.
- Check the profile is removed from the User Profiles window
After pressing yes, you should note that the user profile is gone from the “Profiles stored on this computer:” list. Press “OK” to close it.
- Log back in to the user account to create a new user profile
You can create a new user profile for that account at any time by simply logging into it again. When you do so, Windows 10 will show a “This might take several minutes” prompt.
How to Delete a Windows User Profile from the Registry
If the above method doesn’t work, you can delete a user profile from the registry and via Windows 11 / Windows 10 File Explorer. First, though, sign out of the user and read up on how to safely edit the registry.
- Delete the Windows 11 / Windows 10 user profile via File Explorer
Head to the
C:\Users
folder and look for the user profile you want to remove. Click it, then press “Delete”. - Press “Continue” on UAC prompt
- Open the Registry editor
Press the “Start” button and type “regedit”, then click “Run as administrator”.
- Navigate to the profile list in registry editor
In the search bar or side menu, navigate to the profile list in registry editor, which is found at:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\ProfileList
- Find the account in the profile list registry key
The profile list registry key will have several SID keys for each user. To find the one you’re looking for, click on each and check the “Data” field next to the “ProfileImagePath” entry.
- Delete the user profile registry key
In the left-hand side menu, right-click the correct user SID and press “Delete”.
- Confirm the user profile registry key deletion
Make sure you’re deleting the key for the correct user before clicking “Yes”.
FAQ – Frequently Asked Questions about Windows User Profiles
How can I back up a user profile before deleting it in Windows 10 or 11?
Use Windows Backup and Restore feature to create a system image or manually copy the user folder from C:\Users\ to another location. Ensure all necessary files are included in the backup.
What are the implications of deleting a user profile on shared documents and desktop items?
Items stored in a user’s profile, including documents and desktop items, will be permanently deleted. Shared items located in public folders or other user profiles won’t be affected.
Can I delete a user profile to fix a login issue without deleting the account?
Yes, deleting just the profile can often resolve login problems by allowing Windows to create a fresh profile on the next login, without affecting the user’s account.
How do I manage user accounts and profiles in a family or shared computer setup?
Use Windows Settings to create separate accounts for each user, allowing for individual profiles, settings, and parental controls if necessary. This ensures a personalized and secure environment for each user.
What steps should I take if I’m unable to delete a user profile through the usual methods?
Restart your computer in Safe Mode and try deleting the profile again, or use a third-party software designed to clean up user profiles and registry entries.
How do I restore a user profile that was accidentally deleted?
If you have a backup, you can restore the user’s data by copying it back to the C:\Users\ directory. Restoring the profile settings exactly as they were might not be possible without a system restore point.
Can I delete a user profile to free up disk space?
Yes, deleting user profiles can free up disk space, especially if the profiles contain large files or have accumulated a lot of data over time.
How do I change the default location of user profiles in Windows 10 or Windows 11?
This involves editing the registry or using Group Policy, and it’s a complex process that can affect system stability. It’s typically recommended only for advanced users or IT professionals.
What should I do if a user profile deletion fails due to file permission issues?
Ensure you have administrative rights, take ownership of the files or folders in question, or check for any open files and applications that might be using the profile.
How does deleting a user profile affect cloud-synced data, like OneDrive or Dropbox?
Data synced with cloud services like OneDrive or Dropbox is not lost when a user profile is deleted, but you’ll need to reconfigure the sync settings when you log in again or set up a new profile.
Can I delete all user profiles at once in Windows 10 or Windows 11?
While technically possible, it’s risky and not recommended because it includes deleting the default and system profiles, which can render the system unusable or unstable.
How can I ensure that all traces of a user profile are removed from the system?
After deleting the profile via System Properties, manually check the C:\Users\ directory and the registry to ensure all related data and settings are removed.
What are the best practices for managing multiple user profiles on a shared computer?
Regularly back up important data, set clear storage and privacy guidelines, periodically review and clean up unused profiles, and ensure each user logs out after their session.
How can I prevent users from creating new profiles on a Windows 10 or Windows 11 PC?
This can be controlled through Group Policy settings by disabling the “Add or remove user accounts” option and other related settings under User Rights Assignment.
Is it possible to convert a local user profile to a Microsoft account profile without losing data?
Yes, you can link a local account to a Microsoft account through the Settings app under Accounts > Your info. This retains the profile data while enabling sync features and other Microsoft account benefits.
Related: How to Delete a Windows User Account
There are various reasons you might need to delete a user account: maybe the account is no longer needed, you’re preparing to give the computer to someone else, or you simply want to clean up old accounts that are no longer in use. Regardless of the reason, Windows 11 offers several ways to remove user accounts, which we explain in detail in our other guide.
Related: How to Enable the Hidden Administrator Account in Windows 11 and Windows 10
Related: How to Change a Windows Username / Account Name
There are different reasons why you might want to change a username in Windows 11 or Windows 10. Maybe your real name has changed and you need to reflect this change in Windows as well. Or you have been using a nickname and want to do a username change to your real name. In our other guide, we show you how to change a username / account name in Windows.
Last Updated on November 7, 2024 10:44 pm CET
В этой инструкции — пошаговое описание нескольких способов удалить учетную запись Microsoft в Windows 10 в различных ситуациях: когда это единственная учетная запись и вы хотите сделать ее локальной; когда эта учетная запись не нужна. Способы из второго варианта подойдут и для удаления любой локальной учетной записи (кроме системной записи Администратор, которую, однако, можно скрыть). Также в конце статьи присутствует видео инструкция. Также может пригодиться: Как изменить E-mail учетной записи Майкрософт, Как удалить пользователя Windows 10.
В случае если случилось так, что вы не можете войти под своей учетной записью Майкрософт (а также сбросить для нее пароль на сайте MS) и именно по этой причине хотите ее удалить, при этом другой учетной записи нет (если есть — используйте обычный путь удаления), то подсказки о том, как это сделать, активировав скрытую учетную запись администратора (а под ней уже можно и удалить учетку и завести новую) вы можете найти в статье Как сбросить пароль Windows 10.
Как убрать учетную запись Майкрософт и включить вместо нее локальную
Первый, самый простой и заранее предусмотренный в системе способ — просто сделать свою текущую учетную запись локальной с помощью настроек (при этом ваши параметры, настройки оформления и прочее в дальнейшем не будет синхронизироваться на устройствах).
Для того, чтобы сделать это, просто зайдите в Пуск — Параметры (или нажмите клавиши Win+I) — Учетные записи и выберите пункт «Электронная почта и учетные записи». Далее выполните простые шаги. Примечание: предварительно сохраните всю свою работу, так как после отключения аккаунта Майкрософт потребуется выйти из системы.
- Нажмите по пункту «Войти вместо этого с локальной учетной записью».
- Введите текущий пароль учетной записи Майкрософт.
- Введите новые данные, уже для локальной учетной записи (пароль, подсказка, имя учетки, если его нужно изменить).
- После этого вам сообщат о том, что нужно выйти из системы и зайти уже с новой учетной записью.
После выхода и повторного входа в Windows 10, у вас будет использоваться локальная учетная запись.
Как удалить учетную запись Майкрософт (или локальную), если есть другая учетная запись
Второй распространенный случай — в Windows 10 было создано более одной учетной записи, вы пользуетесь локальным аккаунтом, а ненужную учетную запись Майкрософт нужно удалить. Прежде всего, для этого нужно зайти под учетной записью администратора (но не той, что будем удалять, при необходимости предварительно установите права администратора для своей учетной записи).
После этого зайдите в Пуск — Параметры — Учетные записи и выберите пункт «Семья и другие пользователи». Выберите в списке «Другие пользователи» ту учетную запись, которую требуется удалить, кликните по ней и нажмите соответствующую кнопку «Удалить».
Вы увидите предупреждение о том, что вместе с учетной записью в данном случае будут удалены также все данные (файлы на рабочем столе, документы, фото и прочее этого человека — все то, что хранится в C:\Users\Имя_пользователя) этого пользователя (просто данные на дисках никуда не денутся). Если вы предварительно позаботились об их сохранности, нажмите «Удалить учетную запись и данные». Кстати, в следующем способе все данные пользователя можно сохранить.
Через короткий промежуток времени учетная запись Майкрософт будет удалена.
Удаление учетной записи Windows 10 с помощью панели управления
И еще один способ, наверное, самый «естественный». Зайдите в панель управления Windows 10 (включите вид «значки» справа вверху, если там стоит «категории»). Выберите пункт «Учетные записи пользователей». Для дальнейших действий вы должны иметь права администратора в ОС.
- Нажмите «Управление другой учетной записью».
- Выберите учетную запись Майкрософт (подойдет и для локальной), которую требуется удалить.
- Нажмите «Удаление учетной записи».
- Выберите, требуется ли удалить файлы учетной записи или их нужно оставить (при этом, во втором случае они будут перемещены в папку на рабочем столе текущего пользователя).
- Подтвердите удаление учетной записи с компьютера.
Готово, это все, что нужно, чтобы убрать ненужную учетную запись.
Ещё один способ сделать то же самое, из тех, которые подходят для всех редакций Windows 10 (также требуется быть администратором):
- Нажмите клавиши Win+R на клавиатуре
- Введите netplwiz в окно «Выполнить» и нажмите Enter.
- На вкладке «Пользователи» выберите ту учетную запись, которую нужно удалить и нажмите кнопку «Удалить».
После подтверждения удаления, выбранная учетная запись будет удалена.
Удаление учетной записи Майкрософт — видео
Дополнительная информация
Это не все способы, но зато все перечисленные варианты подходят для любой из редакций Windows 10. В профессиональной версии вы можете, например, выполнить эту задачу через «Управление компьютером» — «Локальные пользователи и группы». Также задачу можно выполнить с помощью командной строки (net users).
Если я не учел какой-то из возможных контекстов необходимости удаления учетной записи — спрашивайте в комментариях, я постараюсь подсказать решение.
Администраторы время от времени должны удалять старые профили пользователей (уволенные пользователи, неактивные пользователи, и т.д.) в каталоге 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()}
Поскольку среди пользователей Windows 10 есть новички, только приступившие к знакомству с операционной системой, на нашем сайте появляются инструкции с описанием вещей, которые опытным юзерам уже давно знакомы, понятны и очевидны. В этом гайде уделено внимание вопросам: как удалить пользователя Windows 10; как удалить встроенные учётные записи Администратор и Гость, если появляется сообщение «Пользователь не может быть удален»; что делать, если при входе в систему отображаются два одинаковых пользователя Windows 10.
Обратите внимание, что для совершения всех манипуляций учетная запись должна обладать правами администратора. Сменить их в случае необходимости поможет инструкция Как создать учётную запись пользователя Windows 10. Перед ликвидацией ненужного аккаунта позаботьтесь о том, чтобы в нём не было важных файлов и данных.
Удаление пользователя в Параметрах Windows 10
Если вас пока не сильно тянет искать сложные пути для удаления пользователя в Windows 10, вы можете воспользоваться распространённым и простым способом удаления ненужного пользовательского профиля со своего компьютера.
- Откройте приложение Параметры. Сделать это можно из меню Пуск, либо же сочетанием клавиш Win + I.
- Пройдите в раздел Учетные записи и откройте подраздел Семья и другие люди.
- Перед вами появятся две группы. Во второй, под названием Другие люди, один раз нажмите на аккаунт, который вы хотите убрать, и кликните под ним на Удалить.
- Если в учётной записи юзера не осталось никаких важных файлов или данных, то просто кликните по кнопке Удалить учетную запись и данные.
Удаление пользователя с помощью командной строки
Предпочитаете нестандартно подходить к решению вопроса? Попробуйте удалить пользовательский профиль с помощью командной строки.
- Нажмите на Win + X и выберите пункт Командная строка (администратор), либо же воспользуйтесь комбинацией Win + S, а затем введите Командная строка. Кликните правой кнопкой мышки по результату и произведите запуск от имени администратора.
- Введите net user и запомните точное название аккаунта, который будет подвергнут ликвидации.
- Введите net user username /delete, где username — имя учётной записи, от которой вы хотите избавиться. Если в имени присутствуют пробелы, его нужно взять в двойные кавычки.
Важно: Не стоит таким образом пытаться удалить стандартные профили Администратор и Гость.
Удаление пользователя через Учетные записи пользователей
Ещё один не совсем очевидный вариант — удаление аккаунта с помощью системной утилиты Учетные записи пользователей.
- Нажмите Win + R и введите control userpasswords2.
- Появится окно утилиты. Найдите в нём нужную учётную запись, нажмите на неё и удалите. Если при попытке удаления вы получили ошибку, тогда вам стоит попробовать способ с применением командной строки.
Удаление пользователя через Управление компьютером
Если вам этого мало, вы можете рассмотреть еще один способ удаления лишней учётной записи с помощью Управление компьютером.
- Откройте поиск, нажав на Win + S, и введите Управление компьютером.
- В окне оснастки откройте каталог с записями пользователей.
- Правой кнопкой мышки кликните по нужному юзеру и нажмите Удалить.
Как удалить встроенные учетные записи Администратор и Гость
Если у вас вдруг появилось желание стереть стандартные записи Администратор и Гость, вам не удастся это сделать с помощью вышеописанных вариантов. А всё потому, что эти учётки встроены в систему. Их разве что можно отключить. В этом деле вам поможет инструкция Как отключить или включить учётную запись пользователя Windows 10. Удаление таких учетных записей может Вам понадобиться также в том случае, если вы видите сообщение «Пользователь не может быть удален».
Читайте также: Как создать гостевую учетную запись в Windows 10.
Два одинаковых пользователя Windows 10
Бывают ситуации, когда при входе в Windows 10 отображаются два пользователя с одинаковым именем. Вполне возможно, что этот баг мог появиться в следствии каких-то манипуляций с аккаунтом юзера. Например, после отключения пароля для входа в Windows 10.
В основном данная неисправность устраняется следующим образом:
- Запускается утилита Учетные записи пользователей комбинацией клавиш Win + R – control userpasswords2.
- Включается запрос пароля для этого пользователя и применяется изменение.
- Перезагружается компьютер.
- Отключается запрос пароля в той же утилите.
После всех проделанных телодвижений дубликат учётной записи должен исчезнуть.