windows 批处理脚本:如何检查管理员权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4051883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:42:36  来源:igfitidea点击:

Batch script: how to check for admin rights

windowsbatch-filecmdadmin

提问by flacs

How do I check if the current batch script has admin rights?

如何检查当前批处理脚本是否具有管理员权限?

I know how to make it call itself with runas but not how to check for admin rights. The only solutions I've seen are crude hack jobs or use external programs. Well, actually I don't care if it is a hack job as long as it works on Windows XP and newer.

我知道如何使用 runas 调用它自己,但不知道如何检查管理员权限。我见过的唯一解决方案是粗略的黑客工作或使用外部程序。好吧,实际上我不在乎它是否是黑客工作,只要它适用于 Windows XP 和更新版本即可。

回答by mythofechelon

Issues

问题

blak3r/ Rushyo's solution works fine for everything except Windows 8. Running ATon Windows 8 results in:

blak3r/ Rushyo的解决方案适用于除 Windows 8 以外的所有系统。AT在 Windows 8 上运行会导致:

The AT command has been deprecated. Please use schtasks.exe instead.

The request is not supported.

(see screenshot #1) and will return %errorLevel%1.

(见截图#1)并将返回%errorLevel%1.

 

 

Research

研究

So, I went searching for other commands that require elevated permissions. rationallyparanoid.comhad a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.

所以,我去寻找其他需要提升权限的命令。Reasonlyparanoid.com列出了一些命令,因此我在当前 Windows 操作系统(XP 和 8)的两个相反极端上运行每个命令,希望找到一个命令,当以标准权限运行时,该命令在两个操作系统上都被拒绝访问。

Eventually, I did find one - NET SESSION. A true, clean, universal solution that doesn't involve:

最终,我确实找到了一个 - NET SESSION。一个真正的、干净的、通用的解决方案,不涉及:

  • the creation of or interaction with data in secure locations
  • analyzing data returned from FORloops
  • searching strings for "Administrator"
  • using AT(Windows 8 incompatible) or WHOAMI(Windows XP incompatible).
  • 在安全位置创建数据或与数据交互
  • 分析从FOR循环返回的数据
  • 搜索“管理员”的字符串
  • 使用AT(Windows 8 不兼容)或WHOAMI(Windows XP 不兼容)。

Each of which have their own security, usability, and portability issues.

每个都有自己的安全性、可用性和可移植性问题。

 

 

Testing

测试

I've independently confirmed that this works on:

我已经独立确认这适用于:

  • Windows XP, x86
  • Windows XP, x64
  • Windows Vista, x86
  • Windows Vista, x64
  • Windows 7, x86
  • Windows 7, x64
  • Windows 8, x86
  • Windows 8, x64
  • Windows 10 v1909, x64
  • 视窗 XP、x86
  • 视窗 XP,x64
  • 视窗 Vista,x86
  • Windows Vista,x64
  • 视窗 7、x86
  • 视窗 7,x64
  • 视窗 8、x86
  • 视窗 8,x64
  • Windows 10 v1909,x64

(see screenshot #2)

(见截图#2)

 

 

Implementation / Usage

实施/使用

So, to use this solution, simply do something like this:

因此,要使用此解决方案,只需执行以下操作:

@echo off
goto check_Permissions

:check_Permissions
    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Administrative permissions confirmed.
    ) else (
        echo Failure: Current permissions inadequate.
    )

    pause >nul

Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat

如果您懒惰,请在此处提供:https: //dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat

 

 

Explanation

解释

NET SESSIONis a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."

NET SESSION是一个标准命令,用于“管理服务器计算机连接。不带参数使用,[它]显示有关与本地计算机的所有会话的信息。”

So, here's the basic process of my given implementation:

所以,这是我给定实现的基本过程:

  1. @echo off
    • Disable displaying of commands
  2. goto check_Permissions
    • Jump to the :check_Permissionscode block
  3. net session >nul 2>&1
    • Run command
    • Hide visual output of command by
      1. Redirecting the standard output (numeric handle 1 / STDOUT) stream to nul
      2. Redirecting the standard error output stream (numeric handle 2 / STDERR) to the same destination as numeric handle 1
  4. if %errorLevel% == 0
    • If the value of the exit code (%errorLevel%) is0then this means that no errors have occurredand, therefore, the immediate previous command ran successfully
  5. else
    • If the value of the exit code (%errorLevel%) is not0then this means that errors have occurredand, therefore, the immediate previous command ran unsuccessfully
  6. The code between the respective parenthesis will be executed depending on which criteria is met
  1. @echo off
    • 禁止显示命令
  2. goto check_Permissions
    • 跳转到:check_Permissions代码块
  3. net session >nul 2>&1
    • 运行命令
    • 隐藏命令的视觉输出
      1. 将标准输出(数字句柄 1 / STDOUT)流重定向到nul
      2. 将标准错误输出流(数字句柄 2 / STDERR)重定向到与数字句柄 1 相同的目的地
  4. if %errorLevel% == 0
    • 如果退出代码 ( %errorLevel%) 的值为0那么这意味着没有发生错误,因此,前一个命令成功运行
  5. else
    • 如果退出代码 ( %errorLevel%) 的值不是,0则这意味着发生错误,因此前一个命令未成功运行
  6. 将根据满足的条件执行相应括号之间的代码

 

 

Screenshots

截图

Windows 8 AT%errorLevel%:

视窗 8AT%errorLevel%:

[imgur]

[图像]

 

 

NET SESSIONon Windows XP x86 - Windows 8 x64:

NET SESSION在 Windows XP x86 - Windows 8 x64 上

[imgur]

[图像]

 

 

Thank you, @Tilka, for changing your accepted answer to mine. :)

谢谢@Tilka,将您接受的答案更改为我的答案。:)

回答by blak3r

Anders solution worked for me but I wasn't sure how to invert it to get the opposite (when you weren't an admin).

Anders 解决方案对我有用,但我不确定如何反转它以得到相反的结果(当您不是管理员时)。

Here's my solution. It has two cases an IF and ELSE case, and some ascii art to ensure people actually read it. :)

这是我的解决方案。它有两个案例,IF 和 ELSE 案例,以及一些 ASCII 艺术以确保人们真正阅读它。:)

Minimal Version

最小版本

Rushyo posted this solution here: How to detect if CMD is running as Administrator/has elevated privileges?

Rushyo 在此处发布了此解决方案:如何检测 CMD 是否以管理员身份运行/是否具有提升的权限?

NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
    ECHO Administrator PRIVILEGES Detected! 
) ELSE (
    ECHO NOT AN ADMIN!
)

Version which adds an Error Messages, Pauses, and Exits

添加错误消息、暂停和退出的版本

@rem ----[ This code block detects if the script is being running with admin PRIVILEGES If it isn't it pauses and then quits]-------
echo OFF
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
    ECHO Administrator PRIVILEGES Detected! 
) ELSE (
   echo ######## ########  ########   #######  ########  
   echo ##       ##     ## ##     ## ##     ## ##     ## 
   echo ##       ##     ## ##     ## ##     ## ##     ## 
   echo ######   ########  ########  ##     ## ########  
   echo ##       ##   ##   ##   ##   ##     ## ##   ##   
   echo ##       ##    ##  ##    ##  ##     ## ##    ##  
   echo ######## ##     ## ##     ##  #######  ##     ## 
   echo.
   echo.
   echo ####### ERROR: ADMINISTRATOR PRIVILEGES REQUIRED #########
   echo This script must be run as administrator to work properly!  
   echo If you're seeing this after clicking on a start menu icon, then right click on the shortcut and select "Run As Administrator".
   echo ##########################################################
   echo.
   PAUSE
   EXIT /B 1
)
@echo ON

Works on WinXP --> Win8 (including 32/64 bit versions).

适用于 WinXP --> Win8(包括 32/64 位版本)。

EDIT: 8/28/2012 Updated to support Windows 8. @BenHooper pointed this out in his answer below. Please upvote his answer.

编辑:2012 年 8 月 28 日更新以支持 Windows 8。@BenHooper 在下面的回答中指出了这一点。请为他的回答点赞。

回答by and31415

More issues

更多问题

As pointed out by @Lectrode, if you try to run the net sessioncommand while the Server service is stopped, you receive the following error message:

正如@Lectrode 所指出的,如果您net session在服务器服务停止时尝试运行该命令,您会收到以下错误消息:

The Server service is not started.

More help is available by typing NET HELPMSG 2114

In this case the %errorLevel%variable will be set to 2.

在这种情况下,%errorLevel%变量将设置为2

NoteThe Server service is not started while in Safe Mode (with or without networking).

注意服务器服务在安全模式(有或没有网络)下不会启动。

Looking for an alternative

寻找替代方案

Something that:

一些东西:

  • can be run out of the box on Windows XP and later (32 and 64 bit);
  • doesn't touch the registry or any system file/folder;
  • works regardless of the system locale;
  • gives correct results even in Safe Mode.
  • 可以在 Windows XP 及更高版本(32 位和 64 位)上开箱即用;
  • 不接触注册表或任何系统文件/文件夹;
  • 无论系统语言环境如何都可以工作;
  • 即使在安全模式下也能给出正确的结果。

So I booted a vanilla Windows XP virtual machine and I started scrolling through the list of applications in the C:\Windows\System32folder, trying to get some ideas. After trials and errors, this is the dirty(pun intended) approach I've come up with:

所以我启动了一个普通的 Windows XP 虚拟机,我开始滚动C:\Windows\System32文件夹中的应用程序列表,试图获得一些想法。经过反复试验,这是我想出的肮脏(双关语)方法:

fsutil dirty query %systemdrive% >nul

The fsutil dirtycommand requires admin rights to run, and will fail otherwise. %systemdrive%is an environment variablewhich returns the drive letter where the operating system is installed. The output is redirected to nul, thus ignored. The %errorlevel%variable will be set to 0only upon successful execution.

fsutil dirty命令需要管理员权限才能运行,否则将失败。%systemdrive%是一个环境变量,它返回安装操作系统的驱动器号。输出被重定向到nul,因此被忽略。仅在成功执行后才会将该%errorlevel%变量设置为0

Here is what the documentation says:

以下是文档中的内容:

Fsutil dirty

Queries or sets a volume's dirty bit. When a volume's dirty bit is set, autochkautomatically checks the volume for errors the next time the computer is restarted.

Syntax

fsutil dirty {query | set} <VolumePath>

Parameters

query           Queries the specified volume's dirty bit.
set             Sets the specified volume's dirty bit.
<VolumePath>    Specifies the drive name followed by a colon or GUID.

Remarks

A volume's dirty bit indicates that the file system may be in an inconsistent state. The dirty bit can be set because:

  • The volume is online and it has outstanding changes.
  • Changes were made to the volume and the computer was shut down before the changes were committed to the disk.
  • Corruption was detected on the volume.

If the dirty bit is set when the computer restarts, chkdskruns to verify the file system integrity and to attempt to fix any issues with the volume.

Examples

To query the dirty bit on drive C, type:

fsutil dirty query C:

Fsutil 脏

查询或设置卷的脏位。设置卷的脏位后,autochk 会在下次重新启动计算机时自动检查卷是否有错误。

句法

fsutil dirty {query | set} <VolumePath>

参数

query           Queries the specified volume's dirty bit.
set             Sets the specified volume's dirty bit.
<VolumePath>    Specifies the drive name followed by a colon or GUID.

评论

卷的脏位表示文件系统可能处于不一致状态。可以设置脏位是因为:

  • 卷在线并且它有显着的变化。
  • 对卷进行了更改,并且在将更改提交到磁盘之前关闭了计算机。
  • 在卷上检测到损坏。

如果在计算机重新启动时设置了脏位,则运行chkdsk以验证文件系统完整性并尝试修复卷的任何问题。

例子

要查询驱动器 C 上的脏位,请键入:

fsutil dirty query C:

Further research

进一步的研究

While the solution above works from Windows XP onwards, it's worth adding that Windows 2000 and Windows PE (Preinstalled Environment) don't come with fsutil.exe, so we have to resort to something else.

虽然上述解决方案适用于 Windows XP,但值得补充的是,Windows 2000 和 Windows PE(预安装环境)不附带fsutil.exe,因此我们必须求助于其他方法。

During my previous tests I noticed that running the sfccommand without any parameters would either result in:

在我之前的测试中,我注意到在sfc没有任何参数的情况下运行命令会导致:

  • an error, if you didn't have enough privileges;
  • a list of the available parameters and their usage.
  • 一个错误,如果你没有足够的权限;
  • 可用参数及其用法的列表。

That is: no parameters, no party. The idea is that we can parse the output and check if we got anything but an error:

即:无参数,无party。这个想法是我们可以解析输出并检查我们是否有任何错误:

sfc 2>&1 | find /i "/SCANNOW" >nul

The error output is first redirected to the standard output, which is then piped to the findcommand. At this point we have to look for the onlyparameter that is supported in all Windows versionsince Windows 2000: /SCANNOW. The search is case insensitive, and the output is discarded by redirecting it to nul.

错误输出首先重定向到标准输出,然后通过管道传送到find命令。在这一点上,我们必须寻找自 Windows 2000 以来所有 Windows 版本支持唯一参数:. 搜索不区分大小写,输出将被重定向到./SCANNOWnul

Here's an excerpt from the documentation:

以下是文档的摘录:

Sfc

Scans and verifies the integrity of all protected system files and replaces incorrect versions with correct versions.

Remarks

You must be logged on as a member of the Administrators group to run sfc.exe.

证监会

扫描并验证所有受保护系统文件的完整性,并用正确的版本替换不正确的版本。

评论

您必须以 Administrators 组成员的身份登录才能运行sfc.exe

Sample Usage

示例用法

Here are some paste-and-run examples:

以下是一些粘贴并运行的示例:

Windows XP and later

Windows XP 及更高版本

@echo off

call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)

pause >nul
exit /b

:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b

Windows 2000 / Windows PE

Windows 2000 / Windows PE

@echo off

call :isAdmin
if %errorlevel% == 0 (
echo Running with admin rights.
) else (
echo Error: Access denied.
)

pause >nul
exit /b

:isAdmin
sfc 2>&1 | find /i "/SCANNOW" >nul
exit /b

Applies to

适用于

  • Windows 2000
  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8
  • Windows 8.1
    ---
  • Windows PE
  • 视窗 2000
  • 视窗 XP
  • 视窗Vista
  • Windows 7的
  • 视窗 8
  • 视窗 8.1
    ---
  • 视窗PE

回答by npocmaka

two more ways - fast and backward compatible .

还有两种方式——快速和向后兼容。

fltmc >nul 2>&1 && (
  echo has admin permissions
) || (
  echo has NOT admin permissions
)

fltmccommand is available on every windows system since XP so this should be pretty portable.

fltmc自 XP 以来的每个 Windows 系统上都可以使用命令,因此这应该是非常便携的。



One more really fast solution tested on XP,8.1,7- there's one specific variable =::which is presented only if the console session has no admin privileges.As it is not so easy to create variable that contains =in it's name this is comparatively reliable way to check for admin permission (it does not call external executables so it performs well)

还有一个非常快的解决方案测试上XP8.17-有一个特定的变量=::,其呈现仅在控制台会话没有管理privileges.As也不是那么容易创建一个包含变量=在它的名字,这是检查管理较为可靠的方法权限(它不调用外部可执行文件,因此性能良好)

setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! ( 
   echo has NOT admin permissions
) else (
   echo has admin permissions
)

If you want use this directly through command line ,but not from a batch file you can use:

如果您想直接通过命令行使用它,而不是从批处理文件中使用,您可以使用:

set ^"|find "::"||echo has admin permissions

回答by Anders

>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&(
 echo admin...
)

回答by Lucretius

alternative solution:

替代解决方案:

@echo off
pushd %SystemRoot%
openfiles.exe 1>nul 2>&1
if not %errorlevel% equ 0 (
    Echo here you are not administrator!
) else (
    Echo here you are administrator!
)
popd
Pause

回答by Philm

Not only check but GETTING admin rights automatically
aka Automatic UAC for Win 7/8/8.1 ff.
: The following is a really cool one with one more feature: This batch snippet does not only check for admin rights, but gets them automatically! (and tests before, if living on an UAC capable OS.)

不仅检查而且自动获得管理员权限,
即适用于 Win 7/8/8.1 ff 的自动 UAC。
:下面是一个非常酷的,还有一个功能:这个批处理片段不仅检查管理员权限,而且自动获取它们!(如果生活在支持 UAC 的操作系统上,则之前进行过测试。)

With this trick you don′t need longer to right klick on your batch file "with admin rights". If you have forgotten, to start it with elevated rights, UAC comes up automatically! Moreoever, at first it is tested, if the OS needs/provides UAC, so it behaves correct e.g. for Win 2000/XP until Win 8.1- tested.

使用此技巧,您无需再“以管理员权限”右键单击您的批处理文件。如果您忘记了,以提升的权限启动它,UAC 会自动出现!此外,如果操作系统需要/提供 UAC,首先会对其进行测试,因此它的行为是正确的,例如对于 Win 2000/XP,直到经过 Win 8.1 测试。

@echo off
REM Quick test for Windows generation: UAC aware or not ; all OS before NT4 ignored for simplicity
SET NewOSWith_UAC=YES
VER | FINDSTR /IL "5." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO
VER | FINDSTR /IL "4." > NUL
IF %ERRORLEVEL% == 0 SET NewOSWith_UAC=NO


REM Test if Admin
CALL NET SESSION >nul 2>&1
IF NOT %ERRORLEVEL% == 0 (

    if /i "%NewOSWith_UAC%"=="YES" (
        rem Start batch again with UAC
        echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
        "%temp%\getadmin.vbs"
        del "%temp%\getadmin.vbs"
        exit /B
    )

    rem Program will now start again automatically with admin rights! 
    rem pause
    goto :eof
)

The snippet merges some good batch patterns together, especially (1) the admin test in this thread by Ben Hooper and (2) the UAC activation read on BatchGotAdmin and cited on the batch site by robvanderwoude (respect). (3) For the OS identificaton by "VER | FINDSTR pattern" I just don't find the reference.)

该代码段将一些好的批处理模式合并在一起,尤其是 (1) Ben Hooper 在此线程中的管理测试和 (2) 在 BatchGotAdmin 上读取并在批处理站点上由 robvanderwoude 引用的 UAC 激活(尊重)。(3) 对于“VER | FINDSTR 模式”的操作系统识别,我只是没有找到参考。)

(Concerning some very minor restrictions, when "NET SESSION" do not work as mentioned in another answer- feel free to insert another of those commands. For me running in Windows safe mode or special standard services down and such are not an important use cases- for some admins maybe they are.)

(关于一些非常小的限制,当“NET SESSION”不像另一个答案中提到的那样工作时 - 随意插入另一个命令。对于我在 Windows 安全模式或特殊标准服务下运行,这不是一个重要的用例- 对于某些管理员来说,他们可能是。)

回答by Vitim.us

I have two ways of checking for privileged access, both are pretty reliable, and very portable across almost every windows version.

我有两种检查特权访问的方法,这两种方法都非常可靠,并且几乎可以在每个 Windows 版本中移植。

1. Method

一、方法

set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%

mkdir %WINDIR%\%guid%>nul 2>&1
rmdir %WINDIR%\%guid%>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

This is one of the most reliable methods, because of its simplicity, and the behavior of this very primitive command is very unlikely to change. That is not the case of other built-in CLI tools like net sessionthat can be disabled by admin/network policies, or commands like fsutilsthat changed the output on Windows 10.

这是最可靠的方法之一,因为它很简单,而且这个非常原始的命令的行为不太可能改变。其他内置 CLI 工具(如可由管理员/网络策略禁用的网络会话)或更改 Windows 10 上输出的fsutils 等命令的情况并非如此。

* Works on XP and later

*适用于 XP 及更高版本

2. Method

2. 方法

REG ADD HKLM /F>nul 2>&1

IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)

Sometimes you don't like the idea of touching the user disk, even if it is as inoffensive as using fsutils or creating a empty folder, is it unprovable but it can result in a catastrophic failure if something goes wrong. In this scenario you can just check the registry for privileges.

For this you can try to create a key on HKEY_LOCAL_MACHINEusing default permissions you'll get Access Deniedand the ERRORLEVEL == 1, but if you run as Admin, it will print "command executed successfully"and ERRORLEVEL == 0. Since the key already exists it have no effect on the registry. This is probably the fastest way, and the REGis there for a long time.

* It's not avaliable on pre NT (Win 9X).

有时您不喜欢接触用户磁盘的想法,即使它与使用 fsutils 或创建空文件夹一样无害,是否无法证明,但如果出现问题,可能会导致灾难性的失败。在这种情况下,您只需检查注册表的权限即可。

为此,您可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创建一个密钥,您将获得拒绝访问ERRORLEVEL == 1,但如果您以管理员身份运行,它将打印“命令成功执行”ERRORLEVEL == 0. 由于密钥已经存在,它对注册表没有影响。这可能是最快的方式,REG已经存在很长时间了。

*它在 NT 之前的版本 (Win 9X) 上不可用。

* Works on XP and later

*适用于 XP 及更高版本



Working example

工作示例

A script that clear the temp folder

清除临时文件夹的脚本

@echo off
:main
    echo.
    echo. Clear Temp Files script
    echo.

    call :requirePrivilegies

    rem Do something that require privilegies

    echo. 
    del %temp%\*.*
    echo. End!

    pause>nul
goto :eof


:requirePrivilegies
    set guid=%random%%random%-%random%-%random%-%random%-%random%%random%%random%
    mkdir %WINDIR%\%guid%>nul 2>&1
    rmdir %WINDIR%\%guid%>nul 2>&1
    IF NOT %ERRORLEVEL%==0 (
        echo ########## ERROR: ADMINISTRATOR PRIVILEGES REQUIRED ###########
        echo # This script must be run as administrator to work properly!  #
        echo # Right click on the script and select "Run As Administrator" #
        echo ###############################################################
        pause>nul
        exit
    )
goto :eof

回答by Matt

In the batch script Elevate.cmd(see this link), which I have written to get admin rights, I have done it the following way:

在我为获得管理员权限而编写的批处理脚本Elevate.cmd(请参阅此链接)中,我按以下方式完成:

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

This is tested for Windows 7, 8, 8.1, 10 and even Windows XPand does not need any resource such as a special directory, file or registry key.

这已针对 Windows 7、8、8.1、10 甚至 Windows XP 进行了测试,并且不需要任何资源,例如特殊目录、文件或注册表项。

回答by William

The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:

我发现使用 CMD 脚本检查管理员权限的最干净方法是这样的:

@echo off

REM  Calling verify with no args just checks the verify flag,
REM   we use this for its side effect of setting errorlevel to zero
verify >nul

REM  Attempt to read a particular system directory - the DIR
REM   command will fail with a nonzero errorlevel if the directory is
REM   unreadable by the current process.  The DACL on the
REM   c:\windows\system32\config\systemprofile directory, by default,
REM   only permits SYSTEM and Administrators.
dir %windir%\system32\config\systemprofile >nul 2>nul

REM  Use IF ERRORLEVEL or %errorlevel% to check the result
if not errorlevel 1 echo has Admin privs
if     errorlevel 1 echo has only User privs

This method only uses CMD.exe builtins, so it should be very fast. It also checks for the actual capabilities of the process rather than checking for SIDs or group memberships, so the effectivepermission is tested. And this works as far back as Windows 2003 and XP. Normal user processes or nonelevated processes fail the directory probe, where as Admin or elevated processes succeed.

此方法仅使用 CMD.exe 内置程序,因此速度应该非常快。它还检查进程的实际能力,而不是检查 SID 或组成员身份,因此测试有效权限。这可以追溯到 Windows 2003 和 XP。普通用户进程或未提升的进程无法通过目录探测,而管理员或提升的进程则成功。