如何检测 CMD 是否以管理员身份运行/是否具有提升的权限? [英] How to detect if CMD is running as Administrator/has elevated privileges?

查看:53
本文介绍了如何检测 CMD 是否以管理员身份运行/是否具有提升的权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从批处理文件中,我想测试我是否以管理员/提升权限运行.

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" is selected, so that doesn't work.

如果有一个通用的命令,它没有任何效果,但需要管理权限,那么我可以运行它并检查错误代码以测试权限.到目前为止,我还没有找到这样的命令.我发现的命令似乎返回一个单一的、非特定的错误代码,这可能表明任何事情,并且由于各种原因它们很容易失败.

If there were a universally available command, which has no effect, but requires administrative privileges, then I could run that and check for an error code in order to test for privileges. So far, I haven't found such a command. The commands I have found seem to return a single, non-specific error code, which could indicate anything, and they're prone to failure for a variety of reasons.

我只关心 Windows 7,虽然支持早期的操作系统会很好.

I only care about Windows 7, though support of earlier operating systems would be nice.

推荐答案

ADDENDUM:对于 Windows 8 这将不起作用;请参阅这个很好的答案.

ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.

在此处找到此解决方案:http://www.robvanderwoude.com/clevertricks.php

Found this solution here: http://www.robvanderwoude.com/clevertricks.php

AT > NUL
IF %ERRORLEVEL% EQU 0 (
    ECHO you are Administrator
) ELSE (
    ECHO you are NOT Administrator. Exiting...
    PING 127.0.0.1 > NUL 2>&1
    EXIT /B 1
)

假设这行不通,而且由于我们在谈论 Win7,如果合适,您可以在 Powershell 中使用以下内容:

Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:

$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

如果不是(也可能不是,因为您明确提出了批处理文件),那么您可以在 .NET 中编写上述内容,并根据要使用的批处理文件的结果从 exe 返回退出代码.

If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.

这篇关于如何检测 CMD 是否以管理员身份运行/是否具有提升的权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆