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

查看:349
本文介绍了如何检测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.

推荐答案

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天全站免登陆