[windows] How do you find the current user in a Windows environment?

When running a command-line script, is it possible to get the name of the current user?

This question is related to windows batch-file

The answer is


%USERNAME% is the correct answer in batch and other in Windows environments.

Another option is to use %USERPROFILE% to get the user's path, like C:\Users\username.


Via powershell (file.ps1) I use the following

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name

It returns the name of the user in the "Domain\Username" format. If you just want the username just write

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\")[1]

The advantage is that It works with windows 10 windows 8 server 2016. As far as I remember with also other OS like Win7 etc. (not older) . And yeah via batch you can simply use

 $username = &whoami

%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.

Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:

for /f "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do if /i "%%a %%b"=="User Name:" set _currdomain_user=%%c
for /f "TOKENS=1,2 DELIMS=\" %%a in ("%_currdomain_user%") do set _currdomain=%%a & set _curruser=%%b

Username:

echo %USERNAME%

Domainname:

echo %USERDOMAIN%

You can get a complete list of environment variables by running the command set from the command prompt.


In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find "explorer"] returns a line that contains the explorer.exe process owner's, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.

In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find ">"].


It should be in %USERNAME%. Obviously this can be easily spoofed, so don't rely on it for security.

Useful tip: type set in a command prompt will list all environment variables.


Just use this command in command prompt

C:\> whoami

In most cases, the %USERNAME% variable will be what you want.

echo %USERNAME%

However, if you're running an elevated cmd shell, then %USERNAME% will report the administrator name instead of your own user name. If you want to know the latter, run:

for /f "tokens=2" %u in ('query session ^| findstr /R "^>"') do @echo %u

As far as find BlueBearr response the best (while I,m running my batch script with eg. SYSTEM rights) I have to add something to it. Because in my Windows language version (Polish) line that is to be catched by "%%a %%b"=="User Name:" gets REALLY COMPLICATED (it contains some diacritic characters in my language) I skip first 7 lines and operate on the 8th.

@for /f "SKIP= 7 TOKENS=3,4 DELIMS=\ " %%G in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do @IF %%G==%COMPUTERNAME% set _currdomain_user=%%H

The answer depends on which "command-line script" language you are in.

Cmd

In the old cmd.exe command prompt or in a .bat or .cmd script, you can use the following:

%USERNAME% - Gets just the username.

%USERDOMAIN% - Gets the user's domain.

PowerShell

In the PowerShell command prompt or a .ps1 or .psm1 script, you can use the following:

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name - Gives you the fully qualified username (e.g. Domain\Username). This is also the most secure method because it cannot be overridden by the user like the other $Env variables below.

$Env:Username - Gets just the username.

$Env:UserDomain - Gets the user's domain.

$Env:ComputerName - Gets the name of the computer.


Just type whoami in command prompt and you'll get the current username.


It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:

#include <windows.h>
#include <stdio.h>

int main(int argc, char **argv) {
    printf("%s", GetUserName());
}

And just use that in your batch file.


I use this method in writing batch files for testing.

echo %userdomain%\%username%

Since you must include the password in plain text if authentication is required, I will only use it in a completely private environment where other users cannot view it or if a user seeing the password would bear no consequences.

Hope this helps someone out.


This is the main difference between username variable and whoami command:

C:\Users\user.name>echo %username%
user.name

C:\Users\user.name>whoami
domain\user.name

DOMAIN = bios name of the domain (not fqdn)

Examples related to windows

"Permission Denied" trying to run Python on Windows 10 A fatal error occurred while creating a TLS client credential. The internal error state is 10013 How to install OpenJDK 11 on Windows? I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? git clone: Authentication failed for <URL> How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" XCOPY: Overwrite all without prompt in BATCH Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory how to open Jupyter notebook in chrome on windows Tensorflow import error: No module named 'tensorflow'

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)