如何检查当前的批处理脚本是否具有管理员权限?
我知道如何用runas来称呼自己,但不知道如何检查管理员权限。我所看到的唯一解决方案是粗暴的黑客工作或使用外部程序。好吧,实际上,我不关心它是否是一项hack的工作,只要它可以在Windows XP和更高版本上运行即可。
如何检查当前的批处理脚本是否具有管理员权限?
我知道如何用runas来称呼自己,但不知道如何检查管理员权限。我所看到的唯一解决方案是粗暴的黑客工作或使用外部程序。好吧,实际上,我不关心它是否是一项hack的工作,只要它可以在Windows XP和更高版本上运行即可。
Answers:
blak3r / Rushyo的解决方案适用AT于Windows 8 以外的所有操作系统。在Windows 8上运行会导致:
The AT command has been deprecated. Please use schtasks.exe instead.
The request is not supported.
(请参阅屏幕截图1),然后将返回%errorLevel% 1。
因此,我去寻找其他需要提升权限的命令。Rationallyparanoid.com有一些列表,因此我在当前Windows操作系统(XP和8)的两个相反的极端上运行了每个命令,希望找到一个在使用标准权限运行时两个操作系统都无法访问的命令。
最终,我确实找到了一个- NET SESSION。一个真正的,干净的,通用的解决方案,不涉及:
FOR循环AT(Windows 8不兼容)或WHOAMI(Windows XP不兼容)。  每一个都有其自身的安全性,可用性和可移植性问题。
我已经独立确认此方法适用于:
(请参阅屏幕截图2)
因此,要使用此解决方案,只需执行以下操作:
@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
如果您很懒惰,可以在这里使用:https : //dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat
NET SESSION是用于“管理服务器计算机连接。不带参数使用,[它]显示有关与本地计算机的所有会话的信息”的标准命令。
因此,这是给定实现的基本过程:
@echo off
goto check_Permissions
:check_Permissions代码块net session >nul 2>&1
STDOUT)流重定向到nul STDERR)重定向到与数字句柄1相同的目的地if %errorLevel% == 0
%errorLevel%)的值为, 0则表示没有错误发生,因此前一个命令立即成功运行else
%errorLevel%)的值不是, 0则表示已发生错误,因此前一个命令未成功运行
![[imgur]](https://i.imgur.com/01irE.png)
NET SESSION在Windows XP x86-Windows 8 x64上:
![[imgur]](https://i.stack.imgur.com/cAAIj.png)
谢谢@Tilka,将您接受的答案更改为我的答案。:)
net session成功运行(ERRORLEVEL = 0)-但是他们实际上没有管理员权限。使用openfiles(请参阅下面的Lucretius答案)不会出现此问题。
                    安德斯(Anders)解决方案对我有用,但是我不确定如何将其反转(相反,当您不是管理员时)。
这是我的解决方案。它有IF和ELSE两种情况,以及一些确保人们实际阅读的ascii艺术。:)
Rushyo在此发布了此解决方案:如何检测CMD是否以管理员身份运行/是否具有特权?
NET SESSION >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
    ECHO Administrator PRIVILEGES Detected! 
) ELSE (
    ECHO NOT AN ADMIN!
)
@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
适用于WinXP-> Win8(包括32/64位版本)。
编辑:8/28/2012更新为支持Windows8。@BenHooper在下面的回答中指出了这一点。请支持他的回答。
AT在Windows 8上不起作用,但是我找到了更好的解决方案。实际上,我已经将其发布为答案:stackoverflow.com/questions/4051883/…(或者您可以向下滚动,无论如何)。
                    如@Lectrode所指出的,如果您net session在服务器服务停止时尝试运行该命令,则会收到以下错误消息:
The Server service is not started.
More help is available by typing NET HELPMSG 2114
在这种情况下,%errorLevel%变量将设置为2。
注意在安全模式下(带有或不带有网络),服务器服务不会启动。
一些东西:
因此,我启动了一个香草Windows XP虚拟机,并开始滚动浏览该C:\Windows\System32文件夹中的应用程序列表,以期获得一些想法。经过反复试验,这是我想出的肮脏(双关语)方法:
fsutil dirty query %systemdrive% >nul
该fsutil dirty命令需要管理员权限才能运行,否则将失败。%systemdrive%是一个环境变量,它返回安装操作系统的驱动器号。输出重定向到nul,因此被忽略。仅在成功执行后,%errorlevel%变量才会设置为0。
文档说明如下:
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:
尽管上述解决方案可从Windows XP开始使用,但值得一提的是Windows 2000和Windows PE(预安装环境)不附带 fsutil.exe,因此我们不得不采取其他措施。
在之前的测试中,我注意到运行sfc不带任何参数的命令将导致:
那就是:没有参数,没有党。这个想法是我们可以解析输出并检查是否有除错误以外的任何内容:
sfc 2>&1 | find /i "/SCANNOW" >nul
错误输出首先重定向到标准输出,然后将其通过管道传递给find命令。此时,我们必须查找自Windows 2000以来所有Windows版本都支持的唯一参数:。搜索不区分大小写,并且通过将输出重定向到来放弃输出。/SCANNOWnul
以下是文档摘录:
证监会
扫描并验证所有受保护系统文件的完整性,并将不正确的版本替换为正确的版本。
备注
您必须以Administrators组成员的身份登录才能运行sfc.exe。
以下是一些粘贴并运行的示例:
@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
@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
SFC所有系统上使用支票的任何人,您都需要有所创新。由于某些原因,从Windows 8开始SFC仅输出单个字符。为了成功解析输出,您需要执行以下操作:setlocal enabledelayedexpansion for /f "tokens=* delims=" %%s in ('sfc 2^>^&1^|MORE') do @set "output=!output!%%s" echo "%output%"|findstr /I /C:"/scannow">nul 2>&1(3行)。这在Windows 2000到Windows 2012 R2上都可以使用。附带一提,我更喜欢FINDSTR,因为它通常比FIND更快地处理事物。
                    fsutil解决方案,但是,据我所知,它似乎比我的解决方案灵活得多。虽然,也许不那么优雅。;)我很高兴看到我们之间,我们得到了一套出色,简单且灵活的管理员检测解决方案。:)
                    fsutil dirty query >nul在提升时运行,这会返回一些帮助文本和%errorlevel%= 0
                    fsutil dirty query >nul,但是fsutil dirty query %systemdrive% >nul仍然有效
                    另外两种方式-快速和向后兼容。
fltmc >nul 2>&1 && (
  echo has admin permissions
) || (
  echo has NOT admin permissions
)
fltmc 自XP以来,每个Windows系统上都可以使用该命令,因此该命令应该很容易移植。
还有一个非常快的解决方案测试上XP,8.1,7  -有一个特定的变量=::,其呈现仅在控制台会话没有管理privileges.As也不是那么容易创建一个包含变量=在它的名字,这是检查管理较为可靠的方法权限(它不会调用外部可执行文件,因此表现良好)
setlocal enableDelayedExpansion
set "dv==::"
if defined !dv! ( 
   echo has NOT admin permissions
) else (
   echo has admin permissions
)
如果要直接通过命令行使用此命令,而不是批处理文件,则可以使用:
set ^"|find "::"||echo has admin permissions
=::变量的存在是一个bug-它表示一个不存在的驱动器,所以它可能已在win10中修复。–
                    =::是为Windows 10 1709上的非管理员CMD定义的。无论如何,这不是一种可靠的方法,即使在管理员CMD会话上,您也可以轻松地强制对其进行定义:subst :: c:\ & for %a in (::) do %a & set,
                    替代解决方案:
@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
openfiles并检查ERRORLEVEL就足够了。
                    openfiles.exe在WinPE 中不起作用,因此脚本将始终返回该用户不是admin。
                    1>并2>&1在microsoft.com/resources/documentation/windows/xp/all/proddocs/…中进行了说明。nul引用空设备
                    不仅会自动检查,而且会自动获取GET管理员权限,
也称为Win 7/8 / 8.1及以下版本的UAC。:以下是一个非常酷的功能,另外一个功能是:此批代码段不仅检查管理员权限,而且会自动获取它们!(并在使用UAC的操作系统上进行测试)。
使用此技巧,您无需再花较长的时间就可以“具有管理员权限”单击批处理文件。如果您忘记了,要以提升的权限启动它,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
)
该代码段将一些良好的批处理模式合并在一起,尤其是(1)Ben Hooper在此线程中进行的admin测试,以及(2)在BatchGotAdmin上读取的UAC激活,并在robbanderwoude的批处理站点上引用(尊重)。(3)对于通过“ VER | FINDSTR模式”进行的操作系统标识,我只是没有找到参考。)
(关于一些非常小的限制,当“ NET SESSION”无法如另一个答案中所述工作时,请随意插入其中的另一个命令。对于我来说,以Windows安全模式运行或运行特殊标准服务时,这不是重要的用例。 -也许是某些管理员。)
start-它在新窗口中打开脚本。如果要查看结果,请在pause脚本末尾添加一个。另外,很难检测到何时“停留”在高架上以及何时重新运行。您可以为此使用命令行参数:github.com/tgandor/meats/blob/master/lang_lawyer/cmd/…–
                    我有两种检查特权访问的方法,两种方法都非常可靠,并且几乎可以在所有Windows版本中移植。
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!
)
由于其简单性,这是最可靠的方法之一,并且此非常原始的命令的行为极不可能更改。其他内置CLI工具(例如可以通过管理员/网络策略禁用的网络会话)或更改Windows 10上的输出的命令诸如fsutils则不是这种情况。
* 适用于XP和更高版本
REG ADD HKLM /F>nul 2>&1
IF %ERRORLEVEL%==0 (
    ECHO PRIVILEGED!
) ELSE (
    ECHO NOT PRIVILEGED!
)
有时您不喜欢触摸用户磁盘的想法,即使它像使用fsutils或创建一个空文件夹一样廉价,它是否无法证明,但是如果出了问题,可能会导致灾难性的失败。在这种情况下,您可以只检查注册表中的特权。
为此,您可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创建密钥,您将获得Access Denied和
ERRORLEVEL == 1,但是如果您以Admin身份运行,它将打印“命令执行成功”和ERRORLEVEL == 0。由于该密钥已经存在,因此对注册表没有任何影响。这可能是最快的方法,并且REG已经存在很长时间了。* 在pre NT(Win 9X)上不可用。
* 适用于XP和更高版本
清除临时文件夹的脚本
我发现,使用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此方法仅使用CMD.exe内置函数,因此它应该非常快。它还检查流程的实际功能,而不是检查SID或组成员身份,因此将测试有效权限。这可以追溯到Windows 2003和XP。普通用户进程或非提升进程使目录探测失败,而Admin或提升进程成功。
以下尝试在Windows目录中创建文件。如果成功,它将删除它。
copy /b/y NUL %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
if errorlevel 1 goto:nonadmin
del %WINDIR%\06CF2EB6-94E6-4a60-91D8-AB945AE8CF38 >NUL 2>&1
:admin
rem here you are administrator
goto:eof
:nonadmin
rem here you are not administrator
goto:eof
请注意,06CF2EB6-94E6-4a60-91D8-AB945AE8CF38是今天生成的GUID,并且假定它不可能与现有文件名冲突。
was generated today and it is assumed to be improbable to conflict with an existing filename.除非两个人使用此代码
                    whoami / groups在一种情况下不起作用。如果您完全关闭了UAC(不仅关闭了通知),而且从管理员提示开始,然后发出:
runas /trustlevel:0x20000 cmd
您将在非高架运行,但发出:
whoami /groups
会说你被提升。这是错的。这是错误的原因:
在这种状态下运行时,如果IsUserAdmin(https://msdn.microsoft.com/zh-cn/library/windows/desktop/aa376389 ( v= vs.85 ) .aspx )返回FALSE,并且UAC被完全禁用,并且GetTokenInformation返回TokenElevationTypeDefault(http://blogs.msdn.com/b/cjacks/archive/2006/10/24/modifying-the-mandatory-integrity-level-for-a-securable-object-in-windows-vista.aspx),则表明该进程并未提升运行速度,但whoami /groups声称确实如此。
实际上,从批处理文件执行此操作的最佳方法是:
net session >nul 2>nul
net session >nul 2>nul
echo %errorlevel%
您应该做net session两次,因为如果有人at事先做过,您会得到错误的信息。
whoami /groups没有提供错误的信息。只是这runas /trustlevel使您陷入意外的境地:无需管理员特权即可运行,但具有很高的完整性级别。您可以使用Process Explorer确认。(这可能是错误,runas但不是错误whoami。)
                    runas /trustlevel  当您是本地管理员且UAC已禁用的评论,从管理员提示发出runas命令会将您置于“基本用户”安全上下文中。在这种模式下,您无法执行管理操作。尝试使用“ net session”或fsutil”或任何其他需要管理员访问权限的实用程序。但是,“ whoami / groups”会告诉您您已提升权限。
                    whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
  echo ...  connected as admin
)
whoamiWindows XP不支持Plus 。
                    编辑:copyitright指出这是不可靠的。通过UAC批准读取访问将允许dir成功。我还有更多脚本可提供另一种可能性,但它不是只读的。
reg query "HKLM\SOFTWARE\Foo" >NUL 2>NUL && goto :error_key_exists
reg add "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_not_admin
reg delete "HKLM\SOFTWARE\Foo" /f >NUL 2>NUL || goto :error_failed_delete
goto :success
:error_failed_delete
  echo Error unable to delete test key
  exit /b 3
:error_key_exists
  echo Error test key exists
  exit /b 2
:error_not_admin
  echo Not admin
  exit /b 1
:success
  echo Am admin
下面的旧答案
警告:不可靠
根据此处的许多其他良好答案以及and31415提出的观点,我发现我是以下人群的粉丝:
dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin
很少依赖并且速度很快。
注意:使用cacls检查\ system32 \ config \ system将始终在WOW64中失败(例如,来自%systemroot%\ syswow64 \ cmd.exe / 32位Total Commander),因此在64位系统的32位Shell中运行的脚本将永远循环...最好检查预取目录上的权限:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\"
Win XP to 7经过测试,但是在WinPE中失败,因为在Windows 7 install.wim中没有这样的目录或cacls.exe
同样在winPE中,并且wow64无法通过openfiles.exe检查:
OPENFILES > nul
在Windows 7中,错误级别为“ 1”,信息为“目标系统必须是32位操作系统”
两项检查在恢复控制台中也可能会失败。
什么工作在Windows XP - 8 32/64位,在WOW64和WinPE的是:DIR创建测试(IF管理员没有地毯轰炸与每个人的权限Windows目录...)和
net session
和
reg add HKLM /F
检查。
另外,在某些Windows XP中(还有一些其他版本,也可能取决于管理员的修补工作),另外一个注意事项取决于注册表项,该注册表项直接从.vbs脚本调用bat / cmd将会失败,并且信息表明bat / cmd文件没有任何关联...
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo
另一方面,使用bat / cmd文件的参数调用cmd.exe可以正常工作:
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/C %~s0", "", "runas", 1 >> "%temp%\getadmin.vbs"
cscript "%temp%\getadmin.vbs" //nologo
从字面上看,这个问题以及与之相关的问题以及SE上其他地方的数十个答案(都缺乏这种方式或其他方式)已经清楚地表明Windows无法提供可靠的内置控制台实用程序。因此,是时候推出您自己的了。
以下C代码基于Win2k + 1中的“ 检测程序是否正在以完全管理员权限运行”的原理中的任何位置(无论UAC,域,可传递组...)使用,因为它与系统本身具有相同的功能检查权限。它通过一条消息(可以通过开关将其静音)和退出代码来发出结果信号。
它只需要编译一次,然后就可以在.exe各处复制-它仅取决于kernel32.dll和advapi32.dll(我已经上传了一个副本)。
chkadmin.c:
#include <malloc.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib,"Advapi32.lib")
int main(int argc, char** argv) {
    BOOL quiet = FALSE;
    DWORD cbSid = SECURITY_MAX_SID_SIZE;
    PSID pSid = _alloca(cbSid);
    BOOL isAdmin;
    if (argc > 1) {
        if (!strcmp(argv[1],"/q")) quiet=TRUE;
        else if (!strcmp(argv[1],"/?")) {fprintf(stderr,"Usage: %s [/q]\n",argv[0]);return 0;}
    }
    if (!CreateWellKnownSid(WinBuiltinAdministratorsSid,NULL,pSid,&cbSid)) {
        fprintf(stderr,"CreateWellKnownSid: error %d\n",GetLastError());exit(-1);}
    if (!CheckTokenMembership(NULL,pSid,&isAdmin)) {
        fprintf(stderr,"CheckTokenMembership: error %d\n",GetLastError());exit(-1);}
    if (!quiet) puts(isAdmin ? "Admin" : "Non-admin");
    return !isAdmin;
}1 MSDN声称API是XP +,但这是错误的。CheckTokenMembership 是2k +,而另一个甚至更老。最后一个链接还包含一种甚至在NT中也可以使用的更为复杂的方法。
PowerShell的任何人?
param (
    [string]$Role = "Administrators"
)
#check for local role
$identity  = New-Object Security.Principal.WindowsIdentity($env:UserName)
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
Write-Host "IsInRole('$Role'): " $principal.IsInRole($Role)
#enumerate AD roles and lookup
$groups = $identity::GetCurrent().Groups
foreach ($group in $groups) {
    $trans = $group.Translate([Security.Principal.NTAccount]);
    if ($trans.Value -eq $Role) {
       Write-Host "User is in '$Role' role"
    }
}
这是要添加到列表中的另一个;-)
(尝试在系统位置创建文件)
CD.>"%SystemRoot%\System32\Drivers\etc\_"
MODE CON COLS=80 LINES=25
IF EXIST "%SystemRoot%\System32\Drivers\etc\_" (
  DEL "%SystemRoot%\System32\Drivers\etc\_"
  ECHO Has Admin privileges
) ELSE (
  ECHO No Admin privileges
)
MODE CON没有权限写入系统位置时,将重新初始化屏幕并消除所有文本/错误。
替代方法:使用为此目的而设计的外部实用程序,例如IsAdmin.exe(不受限制的免费软件)。
退出代码:
0-当前用户不是Administrators组的成员
1-管理员的当前用户成员并以提升权限运行
2-管理员的当前用户成员,但未提升权限
@echo off
ver
set ADMDIR=C:\Users\Administrator
dir %ADMDIR% 1>nul 2>&1
echo [%errorlevel%] %ADMDIR%
if "%errorlevel%"=="0" goto main
:: further checks e.g. try to list the contents of admin folders
:: wherever they are stored on older versions of Windows
echo You need administrator privileges to run this script: %0
echo Exiting...
exit /b
:main
echo Executing with Administrator privileges...
@echo off
:start
set randname=%random%%random%%random%%random%%random%
md \windows\%randname% 2>nul
if %errorlevel%==0 (echo You're elevated!!!
goto end)
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
goto start
:end
rd \windows\%randname% 2>nul
pause >nul
我将逐行解释代码:
@echo off
如果不使用此功能,用户将不胜其烦,不止1条线路。
:start
指向程序开始的位置。
set randname=%random%%random%%random%%random%%random%
设置要创建的目录的文件名。
md \windows\%randname% 2>nul
创建目录<DL>:\Windows(用驱动器号替换<DL>)。
if %errorlevel%==0 (echo You're elevated!!!
goto end)
如果ERRORLEVEL环境变量为零,则回显成功消息。
转到结尾(不再继续)。
if %errorlevel%==1 (echo You're not elevated :(:(
goto end)
如果ERRORLEVEL为1,则回显失败消息并转到末尾。
goto start
如果文件名已经存在,请重新创建该文件夹(否则该goto end命令将不允许该文件运行)。
:end
指定终点
rd \windows\%randname% 2>nul
删除创建的目录。
pause >nul
暂停,以便用户可以看到该消息。
注意:>nul和2>nul过滤这些命令的输出。
net user %username% >nul 2>&1 && echo admin || echo not admin
admin
                    我认为最简单的方法是尝试更改系统日期(需要管理员权限):
date %date%
if errorlevel 1 (
   echo You have NOT admin rights
) else (
   echo You have admin rights
)
如果%date%变量可能包含星期几,则只需从DATE命令的最后一部分获取日期:
for /F "delims=" %%a in ('date ^<NUL') do set "today=%%a" & goto break
:break
for %%a in (%today%) do set "today=%%a"
date %today%
if errorlevel 1 ...
:(
                    我发现一个可以使用的用户 net session即使不是管理员。我没有调查原因。我的解决方法是测试用户是否可以在Windows文件夹中创建一个文件夹。
这是我的代码:
::::::: :testadmin function START :::::::
:: this function tests if current user is admin.  results are returned as "true" or "false" in %isadmin%
:: Test "%isadmin" after calling this function
:: Usage: "call :testadmin"
echo Your script entered the :testadmin function by error.  Usage: "call :testadmin"
pause
exit /b
:testadmin
 rd %windir%\local_admin_test > nul 2> nul
 md %windir%\local_admin_test > nul 2> nul
 if [%errorlevel%]==[0] set isadmin=true
 if not [%errorlevel%]==[0] set isadmin=false
 rd %windir%\local_admin_test > nul 2> nul
 if [%isadmin%]==[true] (
   echo User IS admin.
 )
 if not [%isadmin%]==[true] (
   echo User IS NOT admin.
   timeout 30
   :: or use "pause" instead of "timeout"
   exit /b
 )
exit /b
:::::: :testadmin function END ::::::
此页面上四种看似最兼容的方法的集合。第一个真的很天才。从XP开始测试。尽管没有标准命令可用于检查管理员权限,但令人困惑。我想他们现在只是专注于PowerShell,这对我的大部分工作真的没有用。
我将批处理称为“ exit-if-not-admin.cmd”,可以从其他批处理调用该批处理,以确保如果未提供所需的管理员权限,则它们不会继续执行。
rem Sun May 03, 2020
rem Methods for XP+ used herein based on:
rem /programming/4051883/batch-script-how-to-check-for-admin-rights
goto method1
:method1
setlocal enabledelayedexpansion
set "dv==::"
if defined !dv! goto notadmin
goto admin
:method2
call fsutil dirty query %SystemDrive% >nul
if %ERRORLEVEL%==0 goto admin
goto notadmin
:method3
net session >nul 2>&1
if %ERRORLEVEL%==0 goto admin
goto notadmin
:method4
fltmc >nul 2>&1 && goto admin
goto notadmin
:admin
echo Administrator rights detected
goto end
:notadmin
echo ERROR: This batch must be run with Administrator privileges
pause
exit /b
goto end
:end```
这是我的2便士的价值:
我需要一个批处理程序,以便在用户登录过程中的“工作室”环境中在Domain环境中运行,看到用户遵守“锁定”策略和受限制的视图(主要是通过GPO集进行分发)。
在AD用户链接的登录脚本之前,已应用域GPO集,因为尚未创建/加载/未及时准备用户“新”配置文件以准备应用“删除和/或”,因此创建GPO登录脚本的时间过长。固定”任务栏和“开始”菜单项vbscript +添加一些本地文件。
例如:建议的“默认用户”配置文件环境需要在“%ProgramData%\ Microsoft \ Windows \开始菜单\ Programs * MyNewOWA.url *”和“ C:”中放置一个“ .URL”(。lnk)快捷方式。 \ Users \ Public \ Desktop \ * MyNewOWA.url *“位置以及其他项目
用户在域中有多台计算机,只有这些设置的“工作室” PC才需要这些策略。
这些文件夹需要“管理员”权限才能修改,尽管“域用户”是本地“管理员”组的一部分-UAC是下一个挑战。
在这里找到了各种改编作品并合并在一起。我确实有一些使用BYOD设备的用户,以及需要其他文件的烫发问题。尚未在XP上进行过测试(一个较旧的OS),但是该代码已存在,很乐意反馈。
    :: ------------------------------------------------------------------------
    :: You have a royalty-free right to use, modify, reproduce and distribute
    :: the Sample Application Files (and/or any modified version) in any way
    :: you find useful, provided that you agree that the author provides
    :: no warranty, obligations or liability for any Sample Application Files.
    :: ------------------------------------------------------------------------
    :: ********************************************************************************
    ::* Sample batch script to demonstrate the usage of RunAs.cmd
    ::*
    ::* File:           RunAs.cmd
    ::* Date:           12/10/2013
    ::* Version:        1.0.2
    ::*
    ::* Main Function:  Verifies status of 'bespoke' Scripts ability to 'Run As - Admin'
    ::*                 elevated privileges and without UAC prompt
    ::*
    ::* Usage:          Run RunAs.cmd from desired location
    ::*         Bespoke.cmd will be created and called from C:\Utilities location
    ::*         Choose whether to delete the script after its run by removing out-comment
    ::*                 (::) before the 'Del /q Bespoke.cmd' command
    ::*
    ::* Distributed under a "GNU GPL" type basis.
    ::*
    ::* Revisions:
    ::* 1.0.0 - 08/10/2013 - Created.
    ::* 1.0.1 - 09/10/2013 - Include new path creation.
    ::* 1.0.2 - 12/10/2013 - Modify/shorten UAC disable process for Admins
    ::*
    ::* REFERENCES:
    ::* Sample "*.inf" secpol.msc export from Wins 8 x64 @ bottom, 
    ::* Would be default but for 'no password complexities'
    ::*
    ::* To recreate UAC default: 
    ::* Goto:Secpol, edit out Exit, modify .inf set, export as "Wins8x64.inf" 
    ::* and import using secedit cmd provided
    ::*
    :: ********************************************************************************
    @echo off & cls
    color 9F
    Title RUN AS
    Setlocal
    :: Verify local folder availability for script
    IF NOT EXIST C:\Utilities (
        mkdir C:\Utilities & GOTO:GenBatch
    ) ELSE (
        Goto:GenBatch
    )
    :GenBatch
    c:
    cd\
    cd C:\Utilities
    IF NOT EXIST C:\Utilities\Bespoke.cmd (
        GOTO:CreateBatch
    ) ELSE (
        Goto:RunBatch
    )
    :CreateBatch
    Echo. >Bespoke.cmd
    Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
    Echo :: You have a royalty-free right to use, modify, reproduce and distribute >>Bespoke.cmd
    Echo :: the Sample Application Files (and/or any modified version) in any way >>Bespoke.cmd
    Echo :: you find useful, provided that you agree that the author provides >>Bespoke.cmd
    Echo :: has no warranty, obligations or liability for any Sample Application Files. >>Bespoke.cmd
    Echo :: ------------------------------------------------------------------------ >>Bespoke.cmd
    Echo. >>Bespoke.cmd
    Echo :: ******************************************************************************** >>Bespoke.cmd
    Echo ::* Sample batch script to demonstrate the usage of Bespoke.cmd >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* File:           Bespoke.cmd >>Bespoke.cmd
    Echo ::* Date:           10/10/2013 >>Bespoke.cmd
    Echo ::* Version:        1.0.1 >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Main Function:  Allows for running of Bespoke batch with elevated rights and no future UAC 'pop-up' >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Usage:          Called and created by RunAs.cmd run from desired location >>Bespoke.cmd
    Echo ::*                 Found in the C:\Utilities folder >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Distributed under a "GNU GPL" type basis. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Revisions: >>Bespoke.cmd
    Echo ::* 1.0.0 - 09/10/2013 - Created. >>Bespoke.cmd
    Echo ::* 1.0.1 - 10/10/2013 - Modified, added ability to temp disable UAC pop-up warning. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* REFERENCES: >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Exit code (%%^ErrorLevel%%) 0 - No errors have occurred, i.e. immediate previous command ran successfully >>Bespoke.cmd
    Echo ::* Exit code (%%^ErrorLevel%%) 1 - Errors occurred, i.e. immediate previous command ran Unsuccessfully >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* MS OS version check >>Bespoke.cmd
    Echo ::* http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833%28v=vs.85%29.aspx >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Copying to certain folders and running certain apps require elevated perms >>Bespoke.cmd
    Echo ::* Even with 'Run As ...' perms, UAC still pops up. >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* To run a script or application in the Windows Shell >>Bespoke.cmd
    Echo ::* http://ss64.com/vb/shellexecute.html >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo ::* Machines joined to a corporate Domain should have the UAC feature set from, and >>Bespoke.cmd
    Echo ::* pushed out from a DC GPO policy >>Bespoke.cmd
    Echo ::* e.g.: 'Computer Configuration - Policies - Windows Settings - Security Settings -  >>Bespoke.cmd
    Echo ::* Local Policies/Security Options - User Account Control -  >>Bespoke.cmd
    Echo ::* Policy: User Account Control: Behavior of the elevation prompt for administrators >>Bespoke.cmd
    Echo ::*         in Admin Approval Mode  Setting: Elevate without prompting >>Bespoke.cmd
    Echo ::* >>Bespoke.cmd
    Echo :: ******************************************************************************** >>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo @Echo off ^& cls>>Bespoke.cmd
    Echo color 9F>>Bespoke.cmd
    Echo Title RUN AS ADMIN>>Bespoke.cmd
    Echo Setlocal>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo Set "_OSVer=">>Bespoke.cmd
    Echo Set "_OSVer=UAC">>Bespoke.cmd
    Echo VER ^| FINDSTR /IL "5." ^>NUL>>Bespoke.cmd
    Echo IF %%^ErrorLevel%%==0 SET "_OSVer=PreUAC">>Bespoke.cmd
    Echo IF %%^_OSVer%%==PreUAC Goto:XPAdmin>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :: Check if machine part of a Domain or within a Workgroup environment >>Bespoke.cmd
    Echo Set "_DomainStat=">>Bespoke.cmd
    Echo Set "_DomainStat=%%USERDOMAIN%%">>Bespoke.cmd
    Echo If /i %%^_DomainStat%% EQU %%^computername%% (>>Bespoke.cmd
    Echo Goto:WorkgroupMember>>Bespoke.cmd
    Echo ) ELSE (>>Bespoke.cmd
    Echo Set "_DomainStat=DomMember" ^& Goto:DomainMember>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :WorkgroupMember>>Bespoke.cmd
    Echo :: Verify status of Secpol.msc 'ConsentPromptBehaviorAdmin' Reg key >>Bespoke.cmd
    Echo reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin ^| Find /i "0x0">>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo If %%^ErrorLevel%%==0 (>>Bespoke.cmd
    Echo    Goto:BespokeBuild>>Bespoke.cmd
    Echo ) Else (>>Bespoke.cmd
    Echo    Goto:DisUAC>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo :DisUAC>>Bespoke.cmd
    Echo :XPAdmin>>Bespoke.cmd
    Echo :DomainMember>>Bespoke.cmd
    Echo :: Get ADMIN Privileges, Start batch again, modify UAC ConsentPromptBehaviorAdmin reg if needed >>Bespoke.cmd
    Echo ^>nul ^2^>^&1 ^"^%%^SYSTEMROOT%%\system32\cacls.exe^"^ ^"^%%^SYSTEMROOT%%\system32\config\system^">>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo IF ^'^%%^Errorlevel%%^'^ NEQ '0' (>>Bespoke.cmd
    Echo    echo Set objShell = CreateObject^^("Shell.Application"^^) ^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    echo objShell.ShellExecute ^"^%%~s0^"^, "", "", "runas", 1 ^>^> ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    del ^"^%%^temp%%\getadmin.vbs^">>Bespoke.cmd
    Echo    exit /B>>Bespoke.cmd
    Echo ) else (>>Bespoke.cmd
    Echo    pushd ^"^%%^cd%%^">>Bespoke.cmd
    Echo    cd /d ^"^%%~dp0^">>Bespoke.cmd
    Echo    @echo off>>Bespoke.cmd
    Echo )>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo IF %%^_OSVer%%==PreUAC Goto:BespokeBuild>>Bespoke.cmd
    Echo IF %%^_DomainStat%%==DomMember Goto:BespokeBuild>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin /t REG_DWORD /d 0 /f>>Bespoke.cmd
    Echo.>>Bespoke.cmd
    Echo :BespokeBuild>>Bespoke.cmd
    Echo :: Add your script requiring elevated perm and no UAC below: >>Bespoke.cmd
    Echo.>>Bespoke.cmd
    :: PROVIDE BRIEF EXPLINATION AS TO WHAT YOUR SCRIPT WILL ACHIEVE
    Echo ::
    :: ADD THE "PAUSE" BELOW ONLY IF YOU SET TO SEE RESULTS FROM YOUR SCRIPT
    Echo Pause>>Bespoke.cmd
    Echo Goto:EOF>>Bespoke.cmd
    Echo :EOF>>Bespoke.cmd
    Echo Exit>>Bespoke.cmd
    Timeout /T 1 /NOBREAK >Nul
    :RunBatch
    call "Bespoke.cmd"
    :: Del /F /Q "Bespoke.cmd"
    :Secpol
    :: Edit out the 'Exit (rem or ::) to run & import default wins 8 security policy provided below
    Exit
    :: Check if machine part of a Domain or within a Workgroup environment
    Set "_DomainStat="
    Set _DomainStat=%USERDOMAIN%
    If /i %_DomainStat% EQU %computername% (
        Goto:WorkgroupPC
    ) ELSE (
        Echo PC Member of a Domain, Security Policy determined by GPO
        Pause
        Goto:EOF
    )
    :WorkgroupPC
    reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
    Echo.
    If %ErrorLevel%==0 (
        Echo Machine already set for UAC 'Prompt'
        Pause
        Goto:EOF
    ) else (
        Goto:EnableUAC
    )
    :EnableUAC
    IF NOT EXIST C:\Utilities\Wins8x64Def.inf (
        GOTO:CreateInf
    ) ELSE (
        Goto:RunInf
    )
    :CreateInf
    :: This will create the default '*.inf' file and import it into the 
    :: local security policy for the Wins 8 machine
    Echo [Unicode]>>Wins8x64Def.inf
    Echo Unicode=yes>>Wins8x64Def.inf
    Echo [System Access]>>Wins8x64Def.inf
    Echo MinimumPasswordAge = ^0>>Wins8x64Def.inf
    Echo MaximumPasswordAge = ^-1>>Wins8x64Def.inf
    Echo MinimumPasswordLength = ^0>>Wins8x64Def.inf
    Echo PasswordComplexity = ^0>>Wins8x64Def.inf
    Echo PasswordHistorySize = ^0>>Wins8x64Def.inf
    Echo LockoutBadCount = ^0>>Wins8x64Def.inf
    Echo RequireLogonToChangePassword = ^0>>Wins8x64Def.inf
    Echo ForceLogoffWhenHourExpire = ^0>>Wins8x64Def.inf
    Echo NewAdministratorName = ^"^Administrator^">>Wins8x64Def.inf
    Echo NewGuestName = ^"^Guest^">>Wins8x64Def.inf
    Echo ClearTextPassword = ^0>>Wins8x64Def.inf
    Echo LSAAnonymousNameLookup = ^0>>Wins8x64Def.inf
    Echo EnableAdminAccount = ^0>>Wins8x64Def.inf
    Echo EnableGuestAccount = ^0>>Wins8x64Def.inf
    Echo [Event Audit]>>Wins8x64Def.inf
    Echo AuditSystemEvents = ^0>>Wins8x64Def.inf
    Echo AuditLogonEvents = ^0>>Wins8x64Def.inf
    Echo AuditObjectAccess = ^0>>Wins8x64Def.inf
    Echo AuditPrivilegeUse = ^0>>Wins8x64Def.inf
    Echo AuditPolicyChange = ^0>>Wins8x64Def.inf
    Echo AuditAccountManage = ^0>>Wins8x64Def.inf
    Echo AuditProcessTracking = ^0>>Wins8x64Def.inf
    Echo AuditDSAccess = ^0>>Wins8x64Def.inf
    Echo AuditAccountLogon = ^0>>Wins8x64Def.inf
    Echo [Registry Values]>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\CachedLogonsCount=1,"10">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceUnlockLogon=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning=4,5>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption=1,"0">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin=4,5>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorUser=4,3>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableCAD=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableInstallerDetection=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableSecureUIAPaths=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableVirtualization=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeCaption=1,"">>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeText=7,>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\PromptOnSecureDesktop=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ScForceOption=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ShutdownWithoutLogon=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\UndockWithoutLogon=4,1>>Wins8x64Def.inf
    Echo MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ValidateAdminCodeSignatures=4,^0>>Wins8x64Def.inf
    Echo MACHINE\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\AuthenticodeEnabled=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\AuditBaseObjects=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\CrashOnAuditFail=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\DisableDomainCreds=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\FullPrivilegeAuditing=3,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinClientSec=4,536870912>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinServerSec=4,536870912>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\NoLMHash=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymous=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers\AddPrinterDrivers=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactPaths\Machine=7,System\CurrentControlSet\Control\ProductOptions,System\CurrentControlSet\Control\Server Applications,Software\Microsoft\Windows NT\CurrentVersion>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedPaths\Machine=7,System\CurrentControlSet\Control\Print\Printers,System\CurrentControlSet\Services\Eventlog,Software\Microsoft\OLAP Server,Software\Microsoft\Windows NT\CurrentVersion\Print,Software\Microsoft\Windows NT\CurrentVersion\Windows,System\CurrentControlSet\Control\ContentIndex,System\CurrentControlSet\Control\Terminal Server,System\CurrentControlSet\Control\Terminal Server\UserConfig,System\CurrentControlSet\Control\Terminal Server\DefaultUserConfiguration,Software\Microsoft\Windows NT\CurrentVersion\Perflib,System\CurrentControlSet\Services\SysmonLog>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Kernel\ObCaseInsensitive=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management\ClearPageFileAtShutdown=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\ProtectionMode=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\optional=7,Posix>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\AutoDisconnect=4,15>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableForcedLogOff=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionPipes=7,>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RestrictNullSessAccess=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnablePlainTextPassword=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnableSecuritySignature=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\RequireSecuritySignature=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\LDAP\LDAPClientIntegrity=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange=4,^0>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\MaximumPasswordAge=4,30>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireSignOrSeal=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireStrongKey=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SealSecureChannel=4,1>>Wins8x64Def.inf
    Echo MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SignSecureChannel=4,1>>Wins8x64Def.inf
    Echo [Privilege Rights]>>Wins8x64Def.inf
    Echo SeNetworkLogonRight = *S-1-1-0,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeBackupPrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeChangeNotifyPrivilege = *S-1-1-0,*S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551,*S-1-5-90-^0>>Wins8x64Def.inf
    Echo SeSystemtimePrivilege = *S-1-5-19,*S-1-5-32-544>>Wins8x64Def.inf
    Echo SeCreatePagefilePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeDebugPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeRemoteShutdownPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeAuditPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
    Echo SeIncreaseQuotaPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544>>Wins8x64Def.inf
    Echo SeIncreaseBasePriorityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeLoadDriverPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeBatchLogonRight = *S-1-5-32-544,*S-1-5-32-551,*S-1-5-32-559>>Wins8x64Def.inf
    Echo SeServiceLogonRight = *S-1-5-80-0,*S-1-5-83-^0>>Wins8x64Def.inf
    Echo SeInteractiveLogonRight = Guest,*S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeSecurityPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeSystemEnvironmentPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeProfileSingleProcessPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeSystemProfilePrivilege = *S-1-5-32-544,*S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420>>Wins8x64Def.inf
    Echo SeAssignPrimaryTokenPrivilege = *S-1-5-19,*S-1-5-20>>Wins8x64Def.inf
    Echo SeRestorePrivilege = *S-1-5-32-544,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeShutdownPrivilege = *S-1-5-32-544,*S-1-5-32-545,*S-1-5-32-551>>Wins8x64Def.inf
    Echo SeTakeOwnershipPrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeDenyNetworkLogonRight = Guest>>Wins8x64Def.inf
    Echo SeDenyInteractiveLogonRight = Guest>>Wins8x64Def.inf
    Echo SeUndockPrivilege = *S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
    Echo SeManageVolumePrivilege = *S-1-5-32-544>>Wins8x64Def.inf
    Echo SeRemoteInteractiveLogonRight = *S-1-5-32-544,*S-1-5-32-555>>Wins8x64Def.inf
    Echo SeImpersonatePrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
    Echo SeCreateGlobalPrivilege = *S-1-5-19,*S-1-5-20,*S-1-5-32-544,*S-1-5-6>>Wins8x64Def.inf
    Echo SeIncreaseWorkingSetPrivilege = *S-1-5-32-545,*S-1-5-90-^0>>Wins8x64Def.inf
    Echo SeTimeZonePrivilege = *S-1-5-19,*S-1-5-32-544,*S-1-5-32-545>>Wins8x64Def.inf
    Echo SeCreateSymbolicLinkPrivilege = *S-1-5-32-544,*S-1-5-83-^0>>Wins8x64Def.inf
    Echo [Version]>>Wins8x64Def.inf
    Echo signature="$CHICAGO$">>Wins8x64Def.inf
    Echo Revision=1>>Wins8x64Def.inf
    :RunInf
    :: Import 'Wins8x64Def.inf' with ADMIN Privileges, to modify UAC ConsentPromptBehaviorAdmin reg
    >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%%\system32\config\system"
    IF '%Errorlevel%' NEQ '0' (
        echo Set objShell = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
        echo objShell.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
       "%temp%%\getadmin.vbs"
        del "%temp%\getadmin.vbs"
        exit /B
        Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
        Goto:CheckUAC
    ) else (
        Secedit /configure /db secedit.sdb /cfg C:\Utilities\Wins8x64Def.inf /overwrite
        @echo off
    )
    :CheckUAC
    reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v ConsentPromptBehaviorAdmin | Find /i "0x5"
    Echo.
    If %ErrorLevel%==0 (
        Echo ConsentPromptBehaviorAdmin set to 'Prompt'
        Pause
        Del /Q C:\Utilities\Wins8x64Def.inf
        Goto:EOF
    ) else (
        Echo ConsentPromptBehaviorAdmin NOT set to default
        Pause
    )
    ENDLOCAL
    :EOF
    Exit
域PC应尽可能由GPO集控制。工作组/独立计算机可以由此脚本控制。
请记住,在BYOD工作组PC上,UAC提示将至少弹出一次(一旦要求首先提升到“管理员权限”,则必须立即执行),但是从此时起,由于修改了本地安全策略以供管理员使用,因此弹出窗口将消失。
Domain PC应该在“已经”创建的“锁定”策略中设置GPO“ ConsentPromptBehaviorAdmin”策略-如脚本“参考”部分中所述。
再次,如果您对整个“致UAC还是不致UAC”争论不休:-),请运行默认'.inf'文件的secedit.exe导入。
顺便说一句:@boileau在以下方面检查您的失败:
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
通过仅在命令提示符下运行“%SYSTEMROOT%\ system32 \ cacls.exe”或“%SYSTEMROOT%\ system32 \ config \ system”或同时运行这两种方法-是否提升,全面检查结果。
另一种方法。
REM    # # # #      CHECKING OR IS STARTED AS ADMINISTRATOR     # # # # #
FSUTIL | findstr /I "volume" > nul&if not errorlevel 1  goto Administrator_OK
cls
echo *******************************************************
echo ***    R U N    A S    A D M I N I S T R A T O R    ***
echo *******************************************************
echo.
echo.
echo Call up just as the Administrator. Abbreviation can be done to the script and set:
echo.
echo      Shortcut ^> Advanced ^> Run as Administrator
echo.
echo.
echo Alternatively, a single run "Run as Administrator"
echo or in the Schedule tasks with highest privileges
pause > nul
goto:eof
:Administrator_OK
REM Some next lines code ...