I recently needed to make an interactive batch script elevate for admin privileges. I found an example script by jagaroth, and then refined it to make it even more compact. It only writes out one temporary script file, and passes the rest of the required variables on the command line. It can cope with paths containing spaces. It was something of a shell escaping nightmare as you can see from line 14!
@echo off ::Windows XP doesn't have UAC so skip for /f "tokens=3*" %%i in ('reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v ProductName ^| Find "ProductName"') do set WINVER=%%i %%j echo %WINVER% | find "XP" > nul && goto commands ::prompt for elevation if "%1" == "UAC" goto elevation ( echo Set objShell = CreateObject^("Shell.Application"^) echo Set objFSO = CreateObject^("Scripting.FileSystemObject"^) echo strPath = objFSO.GetParentFolderName^(WScript.ScriptFullName^) echo If objFSO.FileExists^("%~0"^) Then echo objShell.ShellExecute "cmd.exe", "/c """"%~0"" UAC ""%~dp0""""", "", "runas", 1 echo Else echo MsgBox "Script file not found" echo End If ) > "%TEMP%\UAC.vbs" cscript //nologo "%TEMP%\UAC.vbs" goto :eof :elevation del /q "%TEMP%\UAC.vbs" :commands ::navigate back to this script's home folder %~d2 cd "%~p2" ::put your main script here echo 1st arg: %1 echo 2nd arg: %2 pause
More simple http://blogmotion.fr/programmation/batch/execute-bat-admin-9842 :)
Great script, just what I was looking for! I’ve spent many hours the past few days tweaking other similar UAC batch scripts. but they all had various inherent flaws while your script works flawlessly as is, without any hassle. I especially appreciate the workaround for paths and filenames with spaces. That was the one big remaining hurdle I simply could not find any solution for myself.
@xhark, what your code does is simply checking whether the script has Admin privileges, nothing more fancy than that. The code on this page on the other hand grants the script Admin privileges via the UAC interface. It’s a whole different ballgame…