tags:

views:

114

answers:

5

When running a command-line script, is it possible to get the name of the current user? The OS is Windows XP.

+3  A: 

You can use the username variable: %USERNAME%

JRL
+11  A: 

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.

the_mandrill
+2  A: 

Username:

echo %USERNAME%

Domainname:

echo %USERDOMAIN%

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

Manga Lee
+2  A: 

It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami and 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.

Chris Kaminski
Yeah, it would have been nice to have a built-in.
Geo
the_mandrill
`whoami` is available starting with Windows Vista.
Joey
True, whoami utility is included with Vista. For XP, it's in the SP2 Support tools and for W2K, it's in the Resource toolkit.
RealHowTo
A: 

%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
BlueBearr