Узнать user id windows

SID (Security IDentifier) – это уникальный идентификатор, который присваивается пользователям, группам, компьютерам или другим объектам безопасности при их создании в Windows или Active Directory. Windows использует SID, а не имя пользователя для контроля доступа к различным ресурсам: сетевым папкам, ключам реестра, объектам файловой системы (NTFS разрешения), принтерам и т.д. В этой статье мы покажем несколько простых способов получить SID пользователя, группы или компьютера, и обратную процедуру – получить объект по известному SID.

Содержание:

  • Что такое SID объекта в Windows?
  • Как получить SID локального пользователя?
  • Узнать SID пользователя или группы в домене Active Directory
  • Получить SID компьютера
  • Как узнать имя пользователя или группы по известному SID?
  • Поиск объектов в Active Directory по SID

Что такое SID объекта в Windows?

Как мы уже сказали, SID (security identifier) позволяет уникально идентифицировать пользовали, группу или компьютер в пределах определенной области (домена или локального компьютера). SID представляет собой строку вида:

S-1-5-21-2927053466-1818515551-28245911311103.
В данном примере:

  • 2927053466-1818515551-2824591131 – это уникальный идентификатор домена, выдавшего SID (у всего объекта в одном домене эта часть будет одинакова)
  • 1103 – относительный идентификатор безопасности объекта (RID). Начинается с 1000 и увеличивается на 1 для каждого нового объекта. Выдается контроллером домена с FSMO ролью RID Master)

SIDы объектов Active Directory хранятся в базе ntds.dit, а SIDы локальных пользователей и групп в локальной базе диспетчера учетных записей Windows (SAM, Security Account Manager в ветке реестра HKEY_LOCAL_MACHINE\SAM\SAM).

В Windows есть так называемые известные идентификаторы безопасности (Well-known SID). Это SID встроенных (BuiltIn) пользователей и групп, которые есть на любых компьютерах Windows. Например:

  • S-1-5-32-544
    – встроенная группу Administrators
  • S-1-5-32-545
    – локальные пользователи
  • S-1-5-32-555
    – группа Remote Desktop Users, которым разрешен вход по RDP
  • S-1-5-domainID-500
    – учетная запись встроенного администратора Windows
  • И т.д.

В Windows можно использовать различные средства для преобразования SID -> Name и Username -> SID: утилиту whoami, wmic, WMI, классы PowerShell или сторонние утилиты.

Как получить SID локального пользователя?

Чтобы получить SID локальной учетной записи, можно воспользоваться утилитой wmic, которая позволяет обратится к пространству имен WMI (Windows Management Instrumentation) компьютера.

wmic useraccount where name='test_user' get sid

Узнать SID пользователя через WMI

Команда может вернуть ошибку, если репозиторий WMI поврежден. Воспользуйтесь этой инструкцией для восстановления WMI репозитория.

Команда вернула SID указанного пользователя —
S-1-5-21-1175651296-1316126944-203051354-1005
.

Чтобы вывести список SID всех локальных пользователей Windows, выполните:

wmic useraccount get name,sid.

Если нужно узнать SID текущего пользователя (под которым выполняется команда), используйте такую команду:

wmic useraccount where name='%username%' get sid

Можно обратится к WMI напрямую из PowerShell:

(Get-CimInstance -Class win32_userAccount -Filter "name='test_user' and domain='$env:computername'").SID

В новых версиях PowerShell Core 7.x вместо команды Get-WmiObject нужно использовать Get-CimInstance.

Но еще проще получить SID локального пользователя с помощью встроенного PowerShell модуля управления локальными пользователями и группами (Microsoft.PowerShell.LocalAccounts).

Get-LocalUser -Name 'test_user' | Select-Object Name, SID

powershell получить sid локалього пользователя в Windows

По аналогии можно получить SID локальной группы:

Get-LocalGroup -Name tstGroup1 | Select-Object Name, SID

Также вы можете использовать.NET классы System.Security.Principal.SecurityIdentifier и System.Security.Principal.NTAccount для получения SID пользователя с помощью PowerShell:

$objUser = New-Object System.Security.Principal.NTAccount("LOCAL_USER_NAME")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

Узнать SID пользователя или группы в домене Active Directory

Вы можете узнать SID своей доменной учетной записи командой:

whoami /user

whoami user getsid

Получить SID пользователя домена Active Directory можно с помощью WMIC. В этом случае в команде нужно указать имя домена:

wmic useraccount where (name='jjsmith' and domain=′corp.winitpro.ru′) get sid

Для получения SID доменного пользователя можно воспользоваться командлетом Get-ADUser, входящего в состав модуля Active Directory Module для Windows PowerShell. Получим SID для доменного пользователя jjsmith:

Get-ADUser -Identity 'jjsmith' | select SID

get-aduser select sid

Вы можете получить SID группы AD с помощью командлета Get-ADGroup:

Get-ADGroup -Filter {Name -like "msk-admin*"} | Select SID

Get-ADGroup получить sid доменной группы

Если на вашем компьютере не установлен модуль AD для PowerShell, вы можете получить SID пользователя с помощью классов .Net:

$objUser = New-Object System.Security.Principal.NTAccount("corp.wintpro.ru","jjsmith")

$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

PowerShell - get SID via SecurityIdentifier and NTAccount

Эта же команда PowerShell в одну строку:

(new-object security.principal.ntaccount “jjsmith").translate([security.principal.securityidentifier])

Получить SID компьютера

Если компьютер с Windows добавлен в домен Active Directory, у него будет два разных SID. Первый SID – идентификатор локального компьютера (Machine SID), а второе – уникальный идентификатор компьютера в AD.

SID компьютера в домене Active Directory можно получить с помощью команды:

Get-ADComputer srv-rds1 -properties sid|select name,sid

get-adcomputer команда для получения SID компьютера в домене Active Directory

SID локального компьютера (Machine SID) можно получить с помощью бесплатной утилиты PsGetsid (https://docs.microsoft.com/en-us/sysinternals/downloads/psgetsid): Но ее придется скачивать и устанавливать на каждый компьютер вручную.

.\PsGetsid64.exe

Или просто, обрезав последние 4 символа RID и SID любого локального пользователя:

$user=(Get-LocalUser Administrator).sid
$user -replace ".{4}$"

PsGetsid6 вывести machine sid локального компьютера

Важно, чтобы у каждого компьютера в домене был уникальный локальный SID. Если вы клонируете компьютеры или виртуальные машины, или создаете их из одного шаблона, то перед тем как добавить их в домен нужно выполнить команду sysprep. Эта утилита сбрасывает локальный Machine SID. Это избавит вас от частых ошибок “Не удалось восстановить доверительные отношения между рабочей станцией и доменом”.

Как узнать имя пользователя или группы по известному SID?

Чтобы узнать имя учетной записи пользователя по SID (обратная процедура), можно воспользоваться одной из следующих команд:

wmic useraccount where sid='S-1-3-12-12452343106-3544442455-30354867-1434' get name

Для поиска имени доменного пользователя по SID используйте командлеты из модуля
RSAT-AD-PowerShell
:

Get-ADUser -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Чтобы определить имя группы по известному SID, используйте команду:

Get-ADGroup -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Get-ADGroup найти группу по SID

Также можно узнать получить SID группы и пользователя с помощью встроенных классов PowerShell (без использования дополнительных модулей):

$objSID = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-2470456651-3958312488-29145117-23345716")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value

Поиск объектов в Active Directory по SID

Если вы не знаете к какому типу объекта AD относится SID и какой точно командлет нужно использовать для его поиска (Get-AdUser, Get-ADComputer или Get-ADGroup), вы можете использовать универсальный метод поиска объектов в Active Directory по SID с помощью командлета Get-ADObject

$sid = ‘S-1-5-21-2470146651-3951111111-2989411117-11119501’
Get-ADObject –IncludeDeletedObjects -Filter "objectSid -eq '$sid'" | Select-Object name, objectClass

Get-ADObject поиск объектов в AD по известному SID

В нашем случае объект AD, который имеет данный SID, является компьютером (objectClass=computer).

A Security Identifier (SID) is a unique identifier assigned to each user account in Windows, used to control permissions and manage user access. Knowing the SID of a user can be helpful for various administrative tasks, including troubleshooting permissions issues or configuring settings for specific users. This tutorial provides a step-by-step explanation of how to find the SID of a user in Windows 11 , covering multiple methods for accuracy and convenience.

The SID is crucial in Windows because it uniquely identifies user accounts within the system. If you’re managing permissions, accessing specific settings, or configuring user-specific policies, the SID helps ensure that the correct permissions are applied to the correct user.

Available Methods:

We can find the SID of a user in windows 11 using PowerShell command, Command Prompt Commands, & Registry editor.

PowerShell Commands Command Prompt Commands
GetCurrent WhoAmI
Get-WmiObject wmic useraccount (Current User)
Get-LocalUser wmic useraccount (Specific User)
Get-CimInstance wmic useraccount (User Name)
wmic useraccount (SID of All Users)

Method 1: Find SID of Current User Using the whoami Command:

  • Open Command Prompt by typing “cmd” in the Windows search bar and selecting Run as administrator.

Open Command Prompt using Run as Administrator

Open Command Prompt using Run as Administrator

  • Enter the following command and press Enter:
    • whoami /user

Whoami user command to find SID value

Whoami user command to find SID value

The command will display the Username and SID of the currently active user.

Method 2: Find SID of Current User Using wmic useraccount Command:

  • Open Command Prompt by typing “cmd” in the Windows search bar and selecting Run as administrator.

Open Command Prompt using Run as Administrator

Open Command Prompt using Run as Administrator

  • Enter the command below, replacing UserName with the currently logged-in user’s name:
    • wmic useraccount where name="UserName" get sid

wmic useraccount command to display current user SID Value

wmic useraccount command to display current user SID Value

  • Press Enter, and the SID for the specified user will be displayed.

Method 3: Find SID of Specific User Using wmic useraccount Command:

  • Open Command Prompt by typing “cmd” in the Windows search bar and selecting Run as administrator.

Open Command Prompt using Run as Administrator

Open Command Prompt using Run as Administrator

  • Type the following command, replacing UserName with the username of the account you wish to query:
    • wmic useraccount where name="UserName" get sid

Finding other accounts SID value using command

Finding other accounts SID value using command

  • The SID for the specified user will appear.

Method 4: Find Username for a Given SID Using wmic useraccount Command:

  • Open Command Prompt by typing “cmd” in the Windows search bar and selecting Run as administrator.

Open Command Prompt using Run as Administrator

Open Command Prompt using Run as Administrator

  • Enter the following command, replacing SIDValue with the actual SID:
    • wmic useraccount where sid="SIDValue" get name

Using SID value to find the Username

Using SID value to find the Username

  • You can get the SID value from the above methods.
  • The command will output the Username associated with the specified SID.

Method 5: Find SID of All Users Using wmic useraccount Command:

  • Open Command Prompt by typing “cmd” in the Windows search bar and selecting Run as administrator.

Open Command Prompt using Run as Administrator

Open Command Prompt using Run as Administrator

  • Enter this command:
    • wmic useraccount get name,sid

Command to display all available users and their SID values

Command to display all available users and their SID values

  • This command will display a list of all users and their corresponding SIDs.

Method 6: Find SID of Current User Using GetCurrent in PowerShell:

  • Open PowerShell as Administrator by right-clicking the Start button and selecting Windows Terminal (Admin).

Opening PowerShell as Admin Mode

Opening PowerShell as Admin Mode

  • Enter the following command:
    • [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value

GetCurrent() user command to display current user SID value

GetCurrent() user command to display current user SID value

  • This command will output the SID of the currently logged-in user.

Method 7: Find SID of All Users Using Get-WmiObject in PowerShell:

  • Open PowerShell as Administrator by right-clicking the Start button and selecting Windows Terminal (Admin).

Opening PowerShell as Admin Mode

Opening PowerShell as Admin Mode

  • Run the following command:
    • Get-WmiObject -Class Win32_UserAccount | Select-Object Name, SID

Command will display all list of users and SID values

Command will display all list of users and SID values

  • PowerShell will output a list of usernames along with their corresponding SIDs.

Method 8: Find SID of All Users Using Get-LocalUser in PowerShell:

  • Open PowerShell as Administrator by right-clicking the Start button and selecting Windows Terminal (Admin).

Opening PowerShell as Admin Mode

Opening PowerShell as Admin Mode

  • Run this command:
    • Get-LocalUser | Select-Object Name, SID

Get-LocalUser command to display all users and their SID values

Get-LocalUser command to display all users and their SID values

  • The output will show each user along with their SID.

Note: This command works for local accounts on Windows 11 and is suitable if you don’t require domain user accounts.

Method 9: Find SID of All Users Using Get-CimInstance in PowerShell:

  • Open PowerShell as Administrator by right-clicking the Start button and selecting Windows Terminal (Admin).

Opening PowerShell as Admin Mode

Opening PowerShell as Admin Mode

  • Now you need to execute the following command:
    • Get-CimInstance -ClassName Win32_UserAccount | Select-Object Name, SID

Get-CimInstance command to display all users and their SID values

Get-CimInstance command to display all users and their SID values

Method 10: Find SID of Users in the Registry Editor:

The Registry Editor stores SIDs for each user profile, which can be accessed manually.

  • Press Winkey + R, type regedit, and press Enter to open the Registry Editor.

Running Regedit Command in Run Window

Running Regedit Command in Run Window

  • Navigate to the following path:
    • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Navigate to the desired directory in Registry editor

Navigate to the desired directory in Registry editor

  • Under ProfileList , you’ll find a list of SIDs. Each SID corresponds to a user profile on the system.

UNder Profile list you can find SID values

UNder Profile list you can find SID values

  • Click on each SID folder and check the ProfileImagePath entry to identify which user profile corresponds to each SID.

Caution: Be careful when using the Registry Editor, as making incorrect changes can affect system performance.

Conclusion

Finding the Security Identifier (SID) of a user in Windows 11 is essential for administrators and advanced users who need precise control over permissions and configurations. This tutorial covers several methods to retrieve a user’s SID, including Command Prompt , PowerShell , Registry Editor , and the whoami command. By following these methods, you’ll be able to quickly and accurately identify SIDs for any user account on your system.

Commonly Asking Queries:

Can I change the SID of a user in Windows 11?

No , the SID is unique to each user and is assigned automatically. Changing it can cause access issues and is not recommended.

Is it safe to use the Registry Editor to find SIDs?

Yes , it’s safe to view SIDs in the Registry. However, avoid editing registry entries unless necessary, as incorrect changes can impact system performance.

Does each user have a unique SID across different computers?

No , SIDs are unique within each Windows installation. A user on one computer will have a different SID on another computer.

Why can’t I find a specific SID in the Registry Editor?

If the user account doesn’t have a local profile on the computer, their SID may not appear in the Registry under ProfileList.

What should I do if I accidentally delete or modify a SID in the registry?

Restoring from a recent registry backup or system restore point can often resolve issues if an SID is accidentally modified.

183

183 people found this article helpful

Find a user’s SID with WMIC or in the registry

Updated on January 15, 2022

What to Know

  • In Command Prompt, type wmic useraccount get name,sid and press Enter.
  • You can also determine a user’s SID by looking through the ProfileImagePath values in each S-1-5-21 prefixed SID listed under:
  • HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

A common reason why you might want to find the security identifier (SID) for a user’s account in Windows is to determine which key under HKEY_USERS in the Windows Registry to look for user-specific registry data. Matching SIDs to usernames is easy with the wmic command—available from the Command Prompt in most versions of Windows.

How to Find a User’s SID With WMIC

Follow these easy steps to display a table of usernames and their corresponding SIDs. It’ll probably only take a minute, maybe less, to find a user’s SID in Windows via WMIC:

See How to Find a User’s SID in the Registry further down the page for instructions on matching a username to an SID via information in the Windows Registry, an alternative method to using WMIC. The wmic command didn’t exist before Windows XP, so you’ll have to use the registry method in those older versions of Windows.

  1. Open Terminal (Windows 11), or open Command Prompt in older Windows versions.

    If you’re using a keyboard and mouse in Windows 11/10/8, the fastest way is through the Power User Menu, accessible with the WIN+X shortcut.

    If you don’t see Command Prompt there, type cmd into the search bar in the Start menu, and select Command Prompt when you see it.

    You don’t have to open an elevated Command Prompt for this to work. Some Windows commands require it, but in the WMIC command example below, you can open a regular, non-administrative Command Prompt.

  2. Type the following command into Command Prompt exactly as it’s shown here, including spaces or lack thereof:

     wmic useraccount get name,sid
    

    …and then press Enter.

    If you know the username and would like to grab only that one user’s SID, enter this command but replace USER with the username (keep the quotes):

     wmic useraccount where name="USER" get sid
    

    If you get an error that the wmic command isn’t recognized, change the working directory to be C:\Windows\System32\wbem\ and try again. You can do that with the cd (change directory) command.

  3. You should see a table displayed in Command Prompt. This is a list of each user account in Windows, listed by username, followed by the account’s corresponding SID.

Now that you’re confident a particular user name corresponds to a particular SID, you can make whatever changes you need to in the registry or do whatever else you needed this information for.

Lifewire / Emily Mendoza


Finding the Username Using the SID

If you happen to have a case where you need to find the user name but all you have is the security identifier, you can «reverse» the command like this (just replace this SID with the one in question):

 wmic useraccount where sid="S-1-5-21-992878714-4041223874-2616370337-1001" get name

…to get a result like this:

 Name
jonfi

How to Find a User’s SID in the Registry

You can also determine a user’s SID by looking through the ProfileImagePath values in each S-1-5-21 prefixed SID listed under this key:

 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

The ProfileImagePath value within each SID-named registry key lists the profile directory, which includes the username.

For example, the value under the S-1-5-21-992878714-4041223874-2616370337-1001 key on the computer you see above is C:\Users\jonfi, so we know that’s the SID for that user.

This method of matching users to SIDs will only show those users who are logged in or have logged in and switched users. To continue to use the registry method for determining other user’s SIDs, you’ll need to log in as each user on the system and repeat these steps. This is a big drawback; assuming you’re able, you’re much better off using the wmic command method above.

FAQ

  • Open the Command Prompt by pressing Windows key+R. Then, enter the following command and press Enter: whoami /user.

  • To create a new user account in Windows, go to Start > Settings > Accounts > Family & others users. Under Other users > Add other user, select Add account. Enter the user’s information and follow the prompts.

Thanks for letting us know!

Get the Latest Tech News Delivered Every Day

Subscribe

Загрузить PDF

Загрузить PDF

Из этой статьи вы узнаете, как в Windows выяснить идентификатор безопасности (SID) другого пользователя.

  1. Step 1 Нажмите ⊞ Win+X.

    В левом нижнем углу откроется меню «Опытный пользователь».

  2. Step 2 Нажмите Командная строка (Администратор).

    Откроется новое окно.

  3. Step 3 Щелкните по Да.

    Откроется окно командной строки.

  4. Step 4 Введите WMIC useraccount get name,sid.

    Это команда для отображения идентификаторов безопасности всех пользователей системы.

    • Если вы знаете имя пользователя, введите следующую команду: wmic useraccount where name="USER" get sid (вместо «USER» подставьте имя пользователя).[1]
  5. Step 5 Нажмите ↵ Enter.

    Идентификатор безопасности — это длинная цепочка чисел, которая отобразится справа от каждого имени пользователя.

    Реклама

Об этой статье

Эту страницу просматривали 5005 раз.

Была ли эта статья полезной?

on October 24, 2011

In Windows environment, each user is assigned a unique identifier called Security ID or SID, which is used to control access to various resources like Files, Registry keys, network shares etc. We can obtain SID of a user through WMIC USERACCOUNT command. Below you can find syntax and examples for the same.

Get SID of a local user

wmic useraccount where name='username' get sid

For example, to get the SID for a local user with the login name  ‘John’, the command would be as below

wmic useraccount where name='John' get sid

Get SID for current logged in user

To retrieve the SID for current logged in user we can run the below command. This does not require you to specify the user name in the command. This can be used in batch files which may be executed from different user accounts.

wmic useraccount where name='%username%' get sid

Get SID for current logged in domain user

Run the command ‘whoami /user’ from command line to get the SID for the logged in user.
Example:

c:\>whoami /user
USER INFORMATION
----------------
User Name      SID
============== ==============================================
mydomain\wincmd S-1-5-21-7375663-6890924511-1272660413-2944159
c:\>

Get SID for the local administrator of the computer

wmic useraccount where (name='administrator' and domain='%computername%') get name,sid

Get SID for the domain administrator

wmic useraccount where (name='administrator' and domain='%userdomain%') get name,sid

Find username from a SID
Now this is tip is to find the user account when you have a SID. One of the readers of this post had this usecase and he figured out the command himself with the help of the commands given above. Adding the same here.

wmic useraccount where sid='S-1-3-12-1234525106-3567804255-30012867-1437' get name

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Виртуалка линукс для windows 10
  • List windows services powershell
  • Все версии операционной системы windows
  • Как установить windows 10 на внешний ssd диск с usb разъемом
  • Долгая загрузка windows 10 при включении amd