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

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

我知道如何使自己与runas自己调用,而不是如何检查pipe理员权限。 我见过的唯一的解决scheme是粗糙的黑客工作或使用外部程序。 那么,实际上我不在乎它是否是一个黑客工作,只要它在Windows XP和更新的工作。

问题

blak3r / Rushyo的解决scheme适用于除Windows 8以外的所有应用程序。在Windows 8上运行AT导致:

 The AT command has been deprecated. Please use schtasks.exe instead. The request is not supported. 

(见屏幕截图#1),将返回%errorLevel% 1

研究

所以,我去寻找其他需要提升权限的命令。 理性paranoid.com有一个列表,所以我运行每个命令在当前的Windows操作系统(XP和8)的两个相反的极端,希望find一个命令,将拒绝访问在两个操作系统上运行标准权限。

最终我find了一个 – NET SESSION 。 一个真正的 ,干净的,通用的解决scheme,不涉及:

  • 在安全位置创build数据或与数据交互
  • 分析从FOR循环返回的数据
  • searchstring为“pipe理员”
  • 使用AT (Windows 8不兼容)或WHOAMI (Windows XP不兼容)。

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

testing

我已经独立证实,这工作:

  • Windows XP,x86
  • Windows XP,x64
  • Windows Vista,x86
  • Windows Vista,x64
  • Windows 7,x86
  • Windows 7,x64
  • Windows 8,x86
  • Windows 8,x64

(见截图#2)

实施/使用

所以,要使用这个解决scheme,只需要做这样的事情:

 @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是一个标准的命令,用于“pipe理服务器计算机连接。使用不带参数,它显示所有会话与本地计算机的信息”。

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

  1. @echo off
    • 禁用显示的命令
  2. goto check_Permissions
    • 跳转到:check_Permissions代码块
  3. net session >nul 2>&1
    • 运行命令
    • 隐藏命令的视觉输出
      1. 将标准输出(数字句柄1 / STDOUT )streamredirect到nul
      2. 将标准错误输出stream(数字句柄2 / STDERR )redirect到与数字句柄1相同的目标
  4. if %errorLevel% == 0
    • 如果退出代码( %errorLevel% )的值 0那么这意味着没有错误发生 ,因此,紧接的前一个命令成功运行
  5. else
    • 如果退出代码( %errorLevel% )的值不为 0则表示发生错误 ,因此前一个命令运行失败
  6. 相应括号之间的代码将根据满足哪个标准来执行

截图

Windows 8 AT %errorLevel%

[imgur]

Windows XP x86上的NET SESSION – Windows 8 x64 :

[imgur]

谢谢@蒂尔卡,把你接受的答案改为我的。 🙂

安德斯解决scheme为我工作,但我不知道如何反转它得到相反(当你不是一个pipe理员)。

这是我的解决scheme。 IF和ELSE有两种情况,一种是确保人们真正阅读的ASCII格式。 🙂

最小版本

Rushyo在这里发布了这个解决scheme: 如何检测CMD是否以pipe理员身份运行/具有提升的权限?

 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位版本)。

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

更多的问题

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

 The Server service is not started. More help is available by typing NET HELPMSG 2114 

在这种情况下, %errorLevel%variables将被设置为2

注意服务器服务在安全模式下(无论是否联网)未启动。

寻找替代品

一些东西:

  • 可以在Windows XP及更高版本(32和64位)上运行;
  • 不接触registry或任何系统文件/文件夹;
  • 不pipe系统区域设置如何工作;
  • 即使在安全模式下也能得到正确的结

所以我启动了一个香草的Windows XP虚拟机,并开始在C:\Windows\System32文件夹中滚动浏览应用程序列表,试图获得一些想法。 经过试验和错误,这是我提出的肮脏的 (双关语)方法:

 fsutil dirty query %systemdrive% >nul 

fsutil dirty命令需要pipe理员权限才能运行,否则将失败。 %systemdrive%是一个环境variables ,它返回安装操作系统的驱动器号。 输出redirect到nul ,因此被忽略。 只有成功执行时, %errorlevel%variables才会被设置为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. 

备注

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

  • 该卷在线,并有突出的变化。
  • 在更改提交到磁盘之前,已经对卷进行了更改,并且计算机已closures。
  • 卷上检测到腐败。

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

例子

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

 fsutil dirty query C: 

进一步的研究

虽然上面的解决scheme是从Windows XP开始的,但值得一提的是,Windows 2000和Windows PE(预安装环境)不会随fsutil.exe一起提供,因此我们必须采取其他措施。

在我之前的testing中,我发现运行不带任何参数的sfc命令会导致:

  • 一个错误,如果你没有足够的权限;
  • 可用参数列表及其用法。

那就是:没有参数, 没有派对 。 我们的想法是,我们可以parsing输出,并检查是否有任何错误:

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

错误输出首先被redirect到标准输出,然后输出到find命令。 在这一点上,我们必须寻找自Windows 2000以来在所有Windows版本中支持的唯一参数: /SCANNOW 。 search不区分大小写,并通过将其redirect到nul来丢弃输出。

以下是文档摘录:

证监会

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

备注

您必须以pipe理员组成员的身份login才能运行sfc.exe

样例用法

这里有一些粘贴运行的例子:

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

 @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 

适用于

  • Windows 2000
  • Windows XP
  • Windows Vista
  • Windows 7的
  • Windows 8
  • Windows 8.1
  • Windows PE
 >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"&&( echo admin... ) 

替代scheme:

 @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 

不仅检查,但自动获得pipe理权限
又名自动UAC Win 7/8 / 8.1 ff。 :以下是一个非常酷的一个更多的function:这个批处理片段不仅检查pipe理员权限,但自动获取它们! (如果生活在具有UACfunction的操作系统上,则需要进行testing。)

有了这个技巧,你不需要花更长的时间来敲击你的batch file“使用pipe理员权限”。 如果您忘记了,以更高的权利启动它,UAC会自动启动! 更重要的是,它首先被testing,如果操作系统需要/提供UAC,那么它的行为是正确的,例如Win 2000 / XP,直到Win 8.1testing。

 @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在这个线程中的admintesting和(2)在BatchGotAdmin上读取的UAC激活以及由robvanderwoude(respect)在批处理站点引用的UAC激活。 (3)对于“VER | FINDSTR模式”的操作系统标识我只是没有find参考。)

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

多一个方法

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

fltmc命令是可用的每个Windows系统自XP以来,所以这应该是相当便携。


另外一个在XPtesting的解决scheme, win10 (不幸的是不能在所有的win10机器上工作 – 请参阅注释) – 只有一个特定的variables=::只有当控制台会话没有pipe理权限时才会显示。所以很容易创buildvariables,其中包含=在它的名字这是比较可靠的方式来检查pipe理权限(和很快,因为它不会调用外部可执行文件)

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

我有两种检查特权访问的方式,都是非常可靠的,几乎每个Windows版本都可以移植。

1.方法

 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工具(如可以通过pipe理员/networking策略禁用networking会话)的命令或者诸如更改Windows 10输出的fsutils命令都不是这种情况。

* 适用于XP及更高版本

2.方法

 REG ADD HKLM /F>nul 2>&1 IF %ERRORLEVEL%==0 ( ECHO PRIVILEGED! ) ELSE ( ECHO NOT PRIVILEGED! ) 

有时候你不喜欢触摸用户磁盘的想法,即使它使用fsutils或创build一个空文件夹这样的冒犯,这是不可证实的,但如果出现问题,它可能会导致灾难性的失败。 在这种情况下,你可以检查registry的特权。

为此,您可以尝试使用默认权限在HKEY_LOCAL_MACHINE上创build一个密钥,您将获得Access DeniedERRORLEVEL == 1 ,但是如果以Admin身份运行,则会打印“command executed successfully”ERRORLEVEL == 0 。 由于密钥已经存在,所以对registry没有任何影响。 这可能是最快的方法,而REG在那里已经很久了。

* 在NT之前(Win 9X)不可用。

* 适用于XP及更高版本


工作示例

清除临时文件夹的脚本

 @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 

以下尝试在Windows目录中创build一个文件。 如果它结束,它将会删除它。

 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,假定它不可能与现有的文件名发生冲突。

我发现,使用CMD脚本检查pipe理权限的最简单的方法就是这样的:

 @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内置,所以它应该是非常快的。 它还检查进程的实际function,而不是检查SID或组成员身份,因此testing了有效权限。 这和Windows 2003和XP一样可行。 普通用户进程或非进程进程会使目录探测失败,其中Admin或升级进程成功。

某些服务器会禁用“networking会话”所需的服务。 这会导致pipe理员检查时总是说你没有pipe理员权限。

whoami /小组在一个案件不起作用。 如果UAC完全closures(不仅仅是通知closures), 而且从pipe理员提示符开始,则会发出:

 runas /trustlevel:0x20000 cmd 

你将运行非高架,但发出:

 whoami /groups 

会说你boost了。 这是不对的。 这是为什么它是错的:

在此状态下运行时,如果IsUserAdmin( https://msdn.microsoft.com/en-us/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声称它是。

实际上,从batch file执行此操作的最佳方法是:

 net session >nul 2>nul net session >nul 2>nul echo %errorlevel% 

你应该两次net session ,因为如果有人在手边做了,你会得到错误的信息。

编辑: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 

老答案在下面

警告:不可靠


基于这里和其他一些好的答案,以及由31415提出的观点,我发现我是以下的粉丝:

 dir "%SystemRoot%\System32\config\DRIVERS" 2>nul >nul || echo Not Admin 

几乎没有依赖和快速。

 whoami /groups | find "S-1-16-12288" > nul if not errorlevel 1 ( echo ... connected as admin ) 

注意:使用cacls检查\ system32 \ config \ system将总是在WOW64中失败(例如从%systemroot%\ syswow64 \ cmd.exe / 32位Total Commander),因此在64位系统中运行在32位shell中的脚本将永远循环最好是检查Prefetch目录上的权限:

 >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\Prefetch\" 

赢得XP到7testing,但它在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创buildtesting(IFpipe理员没有地毯轰炸Windows目录与权限的每个人…)和

 net session 

 reg add HKLM /F 

检查。

还有一个注意到一些Windows XP(和其他版本可能也取决于pipe理员的修补),取决于直接从.vbs脚本调用bat / cmd的registry条目将失败,信息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代码基于检测程序是否以完全pipe理员权限运行 ,可以在任何地方和任何情况下(UAC,域,传递组……)在Win2k + 1中 运行 – 因为它和系统本身一样检查权限。 它以消息(可以用开关保持沉默)和退出代码的信号表示结果。

它只需要编译一次,然后你就可以复制到任何地方的.exe – 它只依赖于kernel32.dlladvapi32.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 claims the APIs are XP+ but this is false. CheckTokenMembership is 2k+ and the other one is even older . The last link also contains a much more complicated way that would work even in NT.

PowerShell anyone?

 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" } } 

Here is another one to add to the list 😉

(attempt a file creation in system location)

 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 ) 

The MODE CON reinitializes the screen and surpresses any text/errors when not having the permission to write to the system location.

Alternative: Use an external utility that is designed for this purpose, eg, IsAdmin.exe (unrestricted freeware).

Exit codes:

0 – Current user not member of Administrators group

1 – Current user member of Administrators and running elevated

2 – Current user member of Administrators, but not running elevated

 @echo off ver set ADMDIR=C:\Users\Administrator dir %ADMDIR% 1>nul 2>&1 echo [%errorlevel%] %ADMDIR% if "%errorlevel%"=="0" goto main :: further checks eg 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 

I will explain the code line by line:

 @echo off 

Users will be annoyed with many more than 1 lines without this.

 :start 

Point where the program starts.

 set randname=%random%%random%%random%%random%%random% 

Set the filename of the directory to be created.

 md \windows\%randname% 2>nul 

Creates the directory on <DL>:\Windows (replace <DL> with drive letter).

 if %errorlevel%==0 (echo You're elevated!!! goto end) 

If the ERRORLEVEL environment variable is zero, then echo success message.
Go to the end (don't proceed any further).

 if %errorlevel%==1 (echo You're not elevated :(:( goto end) 

If ERRORLEVEL is one, echo failure message and go to the end.

 goto start 

In case the filename already exists, recreate the folder (otherwise the goto end command will not let this run).

 :end 

Specify the ending point

 rd \windows\%randname% 2>nul 

Remove the created directory.

 pause >nul 

Pause so the user can see the message.

Note : The >nul and 2>nul are filtering the output of these commands.

net user %username% >nul 2>&1 && echo admin || echo not admin

I think the simplest way is trying to change the system date (that requires admin rights):

 date %date% if errorlevel 1 ( echo You have NOT admin rights ) else ( echo You have admin rights ) 

If %date% variable may include the day of week, just get the date from last part of DATE command:

 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 ... 

I found a user that can use net session even though they are not admin. I didn't look into why. My workaround is to test if the user can make a folder in the windows folder.

这是我的代码:

 ::::::: :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 :::::: 

Here's my 2-pennies worth:

I needed a batch to run within a Domain environment during the user login process, within a 'workroom' environment, seeing users adhere to a "lock-down" policy and restricted view (mainly distributed via GPO sets).

A Domain GPO set is applied before an AD user linked login script Creating a GPO login script was too per-mature as the users "new" profile hadn't been created/loaded/or ready in time to apply a "remove and/or Pin" taskbar and Start Menu items vbscript + add some local files.

eg: The proposed 'default-user' profile environment requires a ".URL' (.lnk) shortcut placed within the "%ProgramData%\Microsoft\Windows\Start Menu\Programs*MyNewOWA.url*", and the "C:\Users\Public\Desktop\*MyNewOWA.url*" locations, amongst other items

The users have multiple machines within the domain, where only these set 'workroom' PCs require these policies.

These folders require 'Admin' rights to modify, and although the 'Domain User' is part of the local 'Admin' group – UAC was the next challenge.

Found various adaptations and amalgamated here. I do have some users with BYOD devices as well that required other files with perm issues. Have not tested on XP (a little too old an OS), but the code is present, would love feed back.

  :: ------------------------------------------------------------------------ :: 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, ie immediate previous command ran successfully >>Bespoke.cmd Echo ::* Exit code (%%^ErrorLevel%%) 1 - Errors occurred, ie 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 ::* eg: '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 /QC:\Utilities\Wins8x64Def.inf Goto:EOF ) else ( Echo ConsentPromptBehaviorAdmin NOT set to default Pause ) ENDLOCAL :EOF Exit 

Domain PC's should be governed as much as possible by GPO sets. Workgroup/Standalone machines can be governed by this script.

Remember, a UAC prompt will pop-up at least once with a BYOD workgroup PC (as soon as the first elevating to 'Admin perms' is required), but as the local security policy is modified for admin use from this point on, the pop-ups will disappear.

A Domain PC should have the GPO "ConsentPromptBehaviorAdmin" policy set within your 'already' created "Lock-down" policy – as explained in the script 'REFERENCES' section.

Again, run the secedit.exe import of the default '.inf' file if you are stuck on the whole "To UAC or Not to UAC" debate :-).

btw: @boileau Do check your failure on the:

 >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" 

By running only "%SYSTEMROOT%\system32\cacls.exe" or "%SYSTEMROOT%\system32\config\system" or both from the command prompt – elevated or not, check the result across the board.

Another way to do this.

 REM # # # # CHECKING OR IS STARTED AS ADMINISTRATOR # # # # # FSUTIL | findstr /I "volume" > nul&if not errorlevel 1 goto Administrator_OK cls echo ******************************************************* echo *** RUNASADMINISTRATOR *** 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 ...