on October 28, 2010
In Windows OS, we can find the current logged in username from windows command line. The logged in user information is stored in environment variables. So just by printing the value in these environment variables we can get to know the login name.
To know the login name of the currently logged in user we can run the below command.
echo %username%
This works on all releases of Windows OS(Windows XP, Server 2003, Windows Vista and Windows 7).
There is another command whoami which tells us the domain name also.
whoami
Example:
c:\>whoami cmdline\administrator
Both of these options to find user name can be useful in batch files to write code in such a way that it works for every user. For example, if your batch file need to access a user specific folder, say Application data, then you can refer the directory as ‘C:\users\%username%\appdata‘.
Привет, друзья! Неважно, администрируете ли вы единственный ПК у себя дома или работаете в сфере обслуживания компьютеров под управлением Windows — имя пользователя может понадобиться вам для настройки учётных записей, устранения проблем с доступом клиентских машин или выполнения команд в командной строке.
В этой статье мы рассмотрим несколько способов, как быстро и легко узнать computer username в Windows 11.
Самый простой и быстрый способ – это использование командной строки: Нажмите Win + R, введите cmd и нажмите Enter.
В появившемся окне командной строки введите команду:
whoami
Нажмите Enter.
Система отобразит имя пользователя в формате Имя_компьютера\Имя_пользователя.
Этот метод также работает через командную строку.
Откройте командную строку (Win + R, затем введите cmd и нажмите Enter).
Введите команду:
echo %USERNAME%
Нажмите Enter, и система выведет только имя пользователя.
Откройте «Диспетчер задач» комбинацией клавиш Ctrl + Shift + Esc.
Перейдите во вкладку Пользователи. В списке отобразятся все активные пользователи, включая текущего.
Откройте Параметры (Win + I). Перейдите в раздел Учетные записи.
В разделе Ваши данные будет указано имя учетной записи.
Netplwiz.exe — это интерфейс управления учётными записями пользователей, с его помощью можно просматривать и изменять имена пользователей.
В командной строке или в строке поиска введите Netplwiz.
Откройте PowerShell (Win + R, затем введите powershell и нажмите Enter).
Введите команду:
$env:UserName
Нажмите Enter, и система выведет имя пользователя.
Узнать имя пользователя в Windows 11 оказывается очень просто. Самый быстрый – через команду whoami в командной строке. Однако, если вам удобнее использовать графический интерфейс, вы можете проверить имя через «Параметры» или «Диспетчер задач». Выбирайте тот метод, который удобнее вам!
Download Article
See which user is currently logged into the computer
Download Article
- Using the Start Menu
- Using Command Prompt
|
This wikiHow teaches you how to see your current account’s username on a Windows computer.
- Open your computer’s Start menu.
- Type %USERNAME% into the search box.
- Press Enter.
- Find the current logged-in user in your User Accounts settings.
-
The Start menu button looks like four squares in the lower-left corner of your screen.
-
Click the search box on the Start menu, and enter this line into it. This will search and find the User Accounts application from your Control Panel.
- If %USERNAME% doesn’t bring User Accounts in the search, try searching %ACCOUNT%.
Advertisement
-
This will open your User Accounts window.
-
Your current username is displayed in your User Accounts settings.
Advertisement
-
The Run window allows you to directly open any application or document on your computer.
- You can find and open Run from the Start menu, or press the ⊞ Win+R shortcut on your keyboard.
-
-
This will open Command Prompt in a new window.
-
This command will reply with your username.
-
Your current username will be displayed in a new line.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 28,148 times.
Is this article up to date?
A lot of users are confused about the PowerShell get current username operation. Are you also searching for a guide? In this post, MiniTool will walk you through detailed steps to get user name in PowerShell Windows 11/10/8/7.
As it’s well known to us, PowerShell powerful Windows command-line shell and scripting environment tool. It can be used to deal with many different works such as PowerShell change directory, PowerShell get user group membership, PowerShell copy files, PowerShell install SSH, PowerShell run exe, and more.
However, a lot of users and even experienced professionals still don’t know these PowerShell cmdlets. How do make PowerShell get logged on user? Here’s a true example from the stackoverflow.com forum.
I need to know the logged user name on Windows 10. How do I get the current username in Windows PowerShell? Please help me.
https://stackoverflow.com/questions/2085744/how-do-i-get-the-current-username-in-windows-powershell
What Command Can Be Use to Get Current Username in PowerShell
First of all, it’s necessary to figure out what command can help PowerShell get logged on user. After investigating forums and posts, we find there are many ways to get current username in PowerShell Windows 11/10/8/7. Here we summarize them as follows:
- Windows Environment Variables: There are 3 different cmdlets to interact with the environment variables, including Env PowerShell drive, $env variable, and .NET Environment Class.
- Win32_ComputerSystem Class: Under this class, you can use the Get-WMIObject and Get-CimInstance cmdlets to let PowerShell get username.
- .NET WindowsIdentity Class: You can use the GetCurrentName cmdlet to get the current username on Windows.
- Whoami command: It is an executable file that can be used to find the username in the System32 folder.
- Query command: It can be used to list all currently logged-on user names on the remote computer via the Remote Desktop Protocol.
Now, you should have an overall understanding of the PowerShell get users name cmdlets. Let’s see how to run these cmdlets.
PowerShell Get Current Username on Windows 11/10/8/7
According to the above information, we summarize 5 feasible ways to get username PowerShell in Windows 11/10/8/7. You can choose one based on your preference.
Tips:
Since some cmdlet requires the PowerShell v5.1 and later version, we recommend you keep the PowerShell version up to date. Here you can read this post “How to Update PowerShell Version to v7.2.5 for Windows 10/11”.
# 1. PowerShell Get Current Username via Environment Variables Class
The Windows Environment Variables can detect the username and logged-on user from your system via the following 3 methods.
Way 1. Use Env PowerShell Drive
- Type PowerShell in the search box, and then right-click the Windows PowerShell and select Run as administrator. Then click on Yes to confirm it.
- In the pop-up window, type the following command and hit Enter to get the current logged-on user name.
Get-ChildItem Env:USERNAME
Or
(Get-ChildItem Env:USERNAME).Value (It only returns the username value as a string)
Way 2. Use the $Env Variable
Another simple method is to get the username PowerShell using the $Env variable. To do so, you just need to run the $env:username command in the PowerShell window.
Way 3. Use the .NET Environment Class
Like the $env variable, the .NET Environment class enables you to find the current username value in PowerShell. To make PowerShell get all the last logged users, you can run the command below:
[System.Environment]::UserName
In addition, you can use the GetEnvironmentVariable cmdlet with the Environment class to get the current username.
[System.Environment]::GetEnvironmentVariable(‘username’)
# 2. PowerShell Get Current Username via Win32_ComputerSystem Class
With the Win32_ComputerSystem Class, you can make PowerShell get logged-on users via the Get-WMIObject and Get-CimInstance cmdlets. These cmdlets can help you get information about the username on a local or remote computer via the Windows Management Instrumentation.
To get the current domain and username on a local computer, you can open the PowerShell window and run the following commands:
(Get-WMIObject -ClassName Win32_ComputerSystem).Username
or
(Get-CimInstance -ClassName Win32_ComputerSystem).Username
If you just want to get only the current username without the domain, you can use the split () parameter:
((Get-WMIObject -ClassName Win32_ComputerSystem).Username).Split(”)[1]
# 3. PowerShell Get Current Username via .NET WindowsIdentity Class
The .NET WindowsIdentity Class can also make PowerShell get users name via the GetCurrentName cmdlet. To do so, you just need to run the command below in the PowerShell window.
[System.Security.Principal.WindowsIdentity]::GetCurrent()
To get only the username value, you can use the Split(”) parameter as well:
([System.Security.Principal.WindowsIdentity]::GetCurrent().Name).Split(”)[1]
# 4. PowerShell Get Current Username via the Whoami Command
To get the current username and domain in PowerShell, you just need to run the whoami command. If you just want to get the username only, you can run the (whoami).Split(”)[1] command.
# 5. PowerShell Get Current Username via the Query Command
If you were an administrator or domain user, you can get the logged-on username on a remote computer. For example, if you want to get all logged-on users on a computer named PC1, you can run the qwinsta /server:pc1 command in PowerShell. To show all users with existing log-on sessions, you can run the quser /server:pc1 command.
Further reading: If you enter some issues like file system corruption and low disk space on Windows, don’t worry. MiniTool Partition Wizard can help you fix them easily by checking file system errors, extending/resizing partitions, analyzing disk space, upgrading to a larger hard disk, etc.
Все способы:
- Как узнать имя пользователя
- Способ 1: «Командная строка»
- Способ 2: Панель управления
- Вопросы и ответы: 5
Многие пользователи практикуют использование нескольких учётных записей на одном компьютере – например, в целях родительского контроля. Если аккаунтов много, может возникнуть путаница, поскольку не сразу понятно, под каким из них загружена система. Решить этот вопрос можно просмотром имени текущего пользователя, и сегодня мы хотим вас познакомить с методами совершения этой операции.
Как узнать имя пользователя
В более старых вариантах Виндовс псевдоним учётной записи отображался при вызове меню «Пуск», но разработчики отказались от этого в версии «окон» начиная с 8. В сборках «десятки» до 1803 эта возможность вернулась – имя можно было посмотреть через дополнительное меню «Пуска», доступное по нажатию кнопки с тремя полосками. Однако в 1803 и выше это убрали, и в новейшей сборке Windows 10 доступны иные варианты просмотра имени пользователя, приведём самые простые.
Способ 1: «Командная строка»
Множество манипуляций с системой можно совершить с помощью «Командной строки», в том числе и необходимую нам сегодня.
- Откройте «Поиск» и начните набирать словосочетание командная строка. В меню отобразиться нужное приложение – кликните по нему.
- После открытия интерфейса ввода команд укажите в нем следующий оператор и нажмите Enter:
net user
- Команда выведет на экран список всех учётных записей, созданных на этой системе.
К сожалению, никакого выделения текущего пользователя не предусмотрено, поэтому этот способ подходит только для компьютеров с 1-2 учётными записями.
Способ 2: Панель управления
Второй метод, с помощью которого можно узнать имя пользователя – инструмент «Панель управления».
- Откройте «Поиск», наберите в строке панель управления и кликните по результату.
- Режим отображения значков переключите в «Крупные» и воспользуйтесь пунктом «Учётные записи пользователей».
- Щёлкните по ссылке «Управление другой учётной записью».
- Откроется окно, в котором можно просмотреть все учётные записи, существующие на этом компьютере – справа от аватаров каждой из них можно увидеть имена.
Такой способ удобнее, чем задействование «Командной строки», поскольку применять его можно на любой учётной записи, и информацию указанная оснастка отображает более наглядно.
Мы рассмотрели способы, которыми можно узнать имя пользователя компьютера на Windows 10.
Наша группа в TelegramПолезные советы и помощь