Search code examples
command-prompt

Get display name of current Windows domain user from a command prompt


From the command prompt, how can I get the friendly display name (that is, "John Doe" instead of "john.doe") of the domain user that is currently logged in?


Solution

  • Here is a tricky way that I did it using the net command and the find command in a batch file:

    set command=net user "%USERNAME%" /domain | FIND /I "Full Name"
    
    FOR /F "tokens=1 delims=" %%A in ('%command%') do SET fullNameText=%%A
    set fullName=%fullNameText:Full Name=%
    for /f "tokens=* delims= " %%a in ("%fullName%") do set fullName=%%a
    

    The first line stores the command that we want to execute in a variable. It pulls the username from the environment variables and passes that into the net user command as well as the /domain parameter to tell it to pull from the current domain. Then it pipes the result from that, which is a bunch of data on the current user, to a find method which will pull out only the property that we want. The result of the find is in the format "Full Name John Doe". The second line will execute the command and put the result into the variable fullNameText. The third line will remove the "Full Name" part of the result and end up with " John Doe". The fourth line with the for loop will remove all of the leading spaces from the result and you end up with "John Doe" in the fullName variable.