When running a command-line script, is it possible to get the name of the current user? The OS is Windows XP.
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.
Username:
echo %USERNAME%
Domainname:
echo %USERDOMAIN%
You can get a complete list of environment variables by running the command set
from the command prompt.
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.
%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