Search code examples
windowsbatch-fileadminrunas

How to get just the user name of administrator using batch script in Windows


I want to use "runas /user:admin_name "cmd.exe ....." in my batch script. I need a way to find out precisely the username of the administrator, so that it can be used in "/user:admin_name". If I run "net localgroup administrators", I do get the name of the administrator, but it seems like I have to dig it out from a load of strings as shown in the output below. And this script will be runnning on many different machines which I don't have access to. So, I don't know how exactly the output of "net localgroup administrators" will look like on all the machine configurations. How can I get the name of local administrator without any ambiguity on all Windows machines running NT or Vista or Win-7 ot Win-8 on the network or off the network ?

Alias name administrators Comment Administrators have complete and unrestricted access to the computer/domain

Members


Administrator PETERPAN The command completed successfully.


Solution

  • @ECHO OFF
    SETLOCAL
    SET "admins="
    SET "prev="
    FOR /f "delims=" %%A IN ('net localgroup administrators') DO (
     CALL SET "admins=%%admins%% %%prev%%"
     SET "prev=%%A"
    )
    SET admins=%admins:*- =%
    ECHO admins are "%admins%"
    GOTO :EOF
    

    This should get you a list of administrators from net localgroup administrators