How to detect if CMD is running as Administrator/has elevated privileges?

后端 未结 13 1316
夕颜
夕颜 2020-12-04 07:51

From inside a batch file, I would like to test whether I\'m running with Administrator/elevated privileges.

The username doesn\'t change when \"Run as Administrator\

13条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 08:15

    If you are running as a user with administrator rights then environment variable SessionName will NOT be defined and you still don't have administrator rights when running a batch file.

    You should use "net session" command and look for an error return code of "0" to verify administrator rights.

    Example; - the first echo statement is the bell character net session >nul 2>&1 if not %errorlevel%==0 (echo echo You need to start over and right-click on this file, echo then select "Run as administrator" to be successfull. echo.&pause&exit)

提交回复
热议问题