Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Batch - automatic increase administrative privileges (run as Administrator)

0.00/5 (No votes)
2 Jun 2015 1  
Batch run as Administrator - automatic increase administrative privileges in Batch scripts like BAT and CMD - universal tools Batch_Admin

Introduction

It is intended primarily for Windows system administrators, so workstations and servers.

Is working as an Administrator, you were not annoyed sometimes that you need to keep in mind that requires the batch script to run as "Run as Administrator"? Do you always remember to doing shortcut to a script set in the Batch option of running as Administrator? Do not irritate you that as twice click on the file you would have then some errors and then comes the thought, "Oh yeah, I forgot"?

And what if you simply forget and start a command prompt without elevation, write command to run your script, and perhaps even with some parameters, and here during executing show errors? Well, yes, I know, I know. Then, "Oh yes I forgot." Once again, you run the command prompt as administrator this time and again laboriously type in your command or paste them from the previous window. Not so bad, you can still survive, but ...

What if forgetting previously run the command prompt as administrator, or simply click on your script to run it turns out that set and sequence of commands within the already worked, now something has caused, until she found on the shelf of Windows that require elevated privileges Administrator and beyond Aug. all the spoils. Something already been done and other things have gone wrong. Maybe deleting something where you do not need, do not have any command like this be expected. Now you need to clean this up, "unscrew" and ... start over, or run this time our script as Admministrator. Whew.

That's why I wrote this script once as a batch, custom tool that will easily keep an eye on these matters. The idea was to call it was then as simple, versatile, resistant to some strange calls, working the same way on different Windows systems.

(Forgive me for English)

Using the code

This tools ensures the work on a standard environment, with standard tools and in the same way in different Windows systems. It uses several standard and built-in Windows commands. Do not use any other external scripts. It can be used to call any program as Administrator, not just scripts Batch. It suffices to create a small script, which then call the program that requires permission Administartor. Place this in any search PATH folder (from %PATH%).

This is similar to "run as", but here we do not change a user account, just raise your eligibility Administrators group to the highest privileges as the user Administrator.

To use it, you simply insert the following line (exactly as) in its parent Batch script, which is to be run as Administrator. This is best done at the top of our parent script and it is best that first, which will be called via the CALL further, some sub-scripts (see detailed explanation below).

net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

This can be inserted inside any child scripts, called by CALL syntax.

To display a message while it is still does not have Administrator privileges, eg. for 5 seconds before calling Batch_Admin set the variable ShowAdminInfo on the number of seconds

SET ShowAdminInfo=5
net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

So how it works:

  • Calls UAC.ShellExecute through VBScript to pick up user permissions
  • Batch runs the script, or BAT or CMD
  • Script caller can have a long name spaces included in the call in quotes
  • Give back all the parameters call the master script passed from the command line, as if there was no transmission of the call and start something from scratch, also with special characters, like exclamation marks (!) and percentage (%), and also with parentheses ()
  • Holds a master script location if the call took place in the directory where this script is the master
  • Auxiliary displays a message if we set before ourselves the variable ShowAdminInfo, eg. for 5 seconds which can prevent the immediate passage of the rights of the Administrator giving additional information and the possibility of an informed decision. Examples of setting that must be set: SET ShowAdminInfo=5 By default, because this variable is not defined, it does not display.
  • The script is calling also in the system search path %PATH% and from network resource, such as: \\Computer\share\test.bat
  • Prevents misunderstandings in writing the necessary auxiliary files when the script calls several Batch_Admin almost at the same time. It uses the random number from 1 to 100
  • But, the best is to use it on parent script. The transition to Administrator rights always requires that you run the script completely again, in a new window, in a new environment, without recourse to the the variables are set previously in our script and values of these variables did not pass then to call as Administrator. Just the script will be executed again.

Points of Interest

- Sets one additional variable for use later in the script that causes it when it is in the current directory. See also note below. PATH_BAT - the same path to the location of the script, eg .: C:\UTILS NOTE: If, however, the slave Batch script caused function CALL from one another need to have the correct value of these variables, you have yourself to add two lines (necessary when switching to the Administrator took place in the parent script, because then including a child, as we mentioned above, our Batch_Admin no longer cause and not set properly these variables possibly be old, appropriate for the parent script, and not the slave) - the two row is optional for the transition to this directory and can be combined mark & at the end of the first line:

SET "PATH_BAT=%~dp0"&SET "BatchFullName=%~dpf0"
CD /D "%~dp0"

And now for the best, something that has been added in the new version of Batch_Admin, and which required further description of the operation changes

Why the change?

If you call another script command CALL child and only in the sub-script would be called old Batch_Admin, it's going to raised Administrator rights do not have any transfer of variables from the parent script. Nothing, nothing. Yes, everywhere I've included here to Batch_Admin in the first place, the master script and it's at the top. OK, but what if manipulating scripts but forget about it, or if he placed a call to Batch_Admin in sub-script, and the overarching we set ourselves at least one variable SET command ...? It turns out that inside the latter, sub script by going to the Administrator - nothing will know about setting this variable.

Therefore, now Batch_Admin by default in this helps. Now set (after going to the Administrator), all environment variables and system to the way they were in an environment that user and script host before moving to the Administrator, which somehow restores it to the state before the transition to the Administrator. The exception is the variable TEMP, which by default is left without interference.

But no worries - these changes concern only the current run of the script, not a Windows system settings or general settings on the user's profile. It is not related to one another. Windows and so every time environment creates a setting. However, switching to an Administrator normally would copy settings as Administrator, and for a while before we had our own and a modified copy of the user. We say "copy variables for Administrator privileges" and not "copy variables Administrator", because still asking for a user name in the variable USERNAME gain after raising powers such. John, not Administrator.

Default action:

  • Restores variable SET command set these permissions prior to the transition to Admministrator’s, with the exception of TEMP


The advantages:

  • Moves the next set all the variables are set SET command that were previously, whether entered manually from the command line, or in any of its ancestors batch script which can test a script calling sequentially from the second CALL command, and any further is set Batch_Admin
  • Variable search path PATH is now such as before the transition to the Administrator, or if she'd been wearing modify the master script, this modification is maintained
  • The exception is the variable TEMP, in which Batch_Admin does not interfere, that is, as usual system itself changes (because changes when we move to an Administrator)
  • We get back access to two variables that normally disappear after raising powers to the Administrator:
    • CLIENTNAME   - the name of the remote computer, for example. The name of the station, which was called a terminal session, for example:  COMPUTER-JOHN
    • SESSIONNAME  - the name of the remote session, for example. Terminal session number, for example:   RDP-Tcp#0
  • Other system variables are the same, because when you pick up on the Administrator and so do not change, for example.:

              USERNAME
              USERPROFILE
              HOMEPATH
              APPDATA

Cons:

  • If someone has changed in the parent script typically variable system, such as PATH, it will not have it now "clean" set of variables, and this may be then expected (when using the parameters described below)


Options cancellation and changes:

Just before calling Batch_Admin set the following variables to any value (to only were) and how empty it is by default):

  • $Admin_SET     - prevents definitively restoring SET user variables, which will be new, clean environment variables Administrator
  • $Admin_Temp  - while working to restore the variables, it also restores the variable TEMP, and then it is the same as before the call (by default does not restore)



General principles and calling sub scripts Batch CALL command after changes

NOTE:  Normally, the transition to always require Administrator rights to run the script entirely from scratch in a new window, in a new environment, without reference to the pre-set variables and values of these variables did not pass then to call as Administrator. But .... Batch_Admin in the new version it would do, and transfers these variables and their values to induce the transition as Administrator (see description above). By contrast, still not the variables are set in the sub-script to move to the parent script. Therefore strong recommendation still applies to Batch_Admin cause in the first script and it's parent at the beginning, especially when the call command CALL subsequent scripts. There is no mistake paste the calling line Batch_Admin in each successive, sub-script, because they do in fact Batch_Admin will not be called, or there will be nothing to do, because it is already as Administrator.

Let us therefore specific situation, when bad work and the situation where the well work, after repair
   
Let's start with a bad call. In the example shown here in a second script, "2.bat" get the message
(Valid because it is a new version of Batch_Admin transferring the master variable settings):

[2] Variable_1 - Yes, I know this variable

while the first script 1.bat will not know anything about setting up the second for Variable_2, namely:

[1] Variable_2 - I know nothing of this variable

Repair:  Just first script run as Administrator alone or also in him, that is, in "1.bat" insert at the top of the call Batch_Admin as, how in second script "2.bat":

net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

NOTE:     If the second script "2.bat" remove the front colons in a row
                      :: SET $Admin_SET=Whatever
               then we can test what messages we get, if it was an old Batch_Admin, ie when there is no restoring variables from the parent script

 

The parent script, let's call him 1.BAT

     @echo off
     echo [1] I'm beginning ...&echo.

     SET Variable_1=abc

     CALL 2.BAT

     if     defined Variable_1   echo [1] Variable_1 - Yes, I know this variable
     if not defined Variable_1   echo [1] Variable_1 - I know nothing of this variable
     if     defined Variable_2   echo [1] Variable_2 - Yes, I know this variable
     if not defined Variable_2   echo [1] Variable_2 - I know nothing of this variable
     pause

The child script, let's call him 2.BAT

     @echo off
     REM *** A D M I N I S T R A T O R  ***
     :: SET $Admin_SET=Whatever
     net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*

     SET Variable_2=xyz

     if     defined Variable_1   echo [2] Variable_1 - Yes, I know this variable
     if not defined Variable_1   echo [2] Variable_1 - I know nothing of this variable
     if     defined Variable_2   echo [2] Variable_2 - Yes, I know this variable
     if not defined Variable_2   echo [2] Variable_2 - I know nothing of this variable
     pause

Full source Code of this utils

Copy the following text into Notepad and save it to a disk as:  Batch_Admin.bat

or from article attachment (the attachment script also contains within itself its own full description of the action)

@echo off
(if '%1'=='' SET $Help$=Yes)&(if '%1'=='?' SET $Help$=Yes)&(if '%1'=='/?' SET $Help$=Yes)&(if /I '%1'=='/HELP' SET $Help$=Yes)&(if /I '%1'=='-HELP' SET $Help$=Yes)&(if /I '%1'=='/INFO' SET $Help$=Yes)
if .%$Help$%==.Yes (SET $Help$=&echo *** Batch_Admin ***&echo.&echo Automatically get admin rights for another Batch. See info inside.&TIMEOUT /T 10>nul&(if exist Batch_Admin.bat MORE /C /E +80 Batch_Admin.bat)&pause&goto:eof)

::  A D M I N I S T R A T O R   - Automatically get admin rights for script batch. Paste this on top:    net session >nul 2>nul&if errorlevel 1  Batch_Admin "%~0" %*
::                                Also keep Batch directory localisation and then set variable:   PATH_BAT
::                                if earlier variable "ShowAdminInfo" is empty (not defined) then no info, else showing info with number of seconds
::
::                                Elaboration:  Artur Zgadzaj    Addition informations:  www.widzenia.com/info   (login: info  password: computer)
setlocal
setlocal EnableExtensions
setlocal DisableDelayedExpansion

MD %TEMP% 2> nul
SET /A $Admin_Number=%RANDOM% * 100 / 32768 + 1
SET > "%TEMP%\$Batch_Admin_%$Admin_Number%__SET.TXT"

SET "PATH_BAT=%~dp1"&if not exist "%~1" if not exist "%~1.*" SET "PATH_BAT="

 SET $Parameters=%*
setlocal EnableDelayedExpansion
 SET $Parameters=!$Parameters:%%=%%%%!
setlocal DisableDelayedExpansion

net session >nul 2>nul&if not errorlevel 1  goto Administrator_OK

SET "$Script=%PATH_BAT%%~nx1"
SET "$Script=%$Script:(=^(%"
SET "$Script=%$Script:)=^)%"

if defined ShowAdminInfo   (
   echo.
   echo Script = %$Script%
   echo.
   echo ******************************************************************************
   echo ***   R U N N I N G    A S    A D M I N I S T R A T O R    F O R   Y O U   ***
   echo ******************************************************************************
   echo.
   echo Call up just as the Administrator. You can make a shortcut to the script and set
   echo.
   echo          shortcut ^> Advanced ^> Running as Administrator
   echo.
   echo     Alternatively run once "As Administrator"
   echo     or in the Schedule tasks with highest privileges
   echo.
   echo Cancel Ctrl-C or wait for launch  %ShowAdminInfo%  seconds ...
   TIMEOUT /T %ShowAdminInfo% > nul
   )

SET "Admin_Name=$Batch_Admin_%$Admin_Number%"

SET "Inverted_Commas="
del "%TEMP%\%Admin_Name%_Start.bat" 2>nul
echo %$Parameters% > "%TEMP%\%Admin_Name%_Start.bat"
if not exist "%TEMP%\%Admin_Name%_Start.bat"  SET Inverted_Commas=^"

echo @echo off > "%TEMP%\%Admin_Name%_Start.bat"
echo setlocal DisableDelayedExpansion >> "%TEMP%\%Admin_Name%_Start.bat"
if not defined $Admin_Temp  echo SET TEMP^>^>"%TEMP%\%Admin_Name%__SET.TXT">> "%TEMP%\%Admin_Name%_Start.bat"
if not defined $Admin_SET   echo FOR /F ^"delims=^" %%%%A IN ^(%TEMP%\%Admin_Name%__SET.TXT^) DO SET %%%%A>> "%TEMP%\%Admin_Name%_Start.bat"
echo SET TMP=%%TEMP%%^&SET $Admin_Number=^&SET "PATH_BAT=%PATH_BAT%">> "%TEMP%\%Admin_Name%_Start.bat"
echo del "%TEMP%\%Admin_Name%__*.*" 2^>nul >> "%TEMP%\%Admin_Name%_Start.bat" 
echo CD /D "%CD%" >> "%TEMP%\%Admin_Name%_Start.bat"
echo %$Parameters% %Inverted_Commas% >> "%TEMP%\%Admin_Name%_Start.bat"

echo SET UAC = CreateObject^("Shell.Application"^)                         > "%TEMP%\%Admin_Name%__getPrivileges.vbs"
echo UAC.ShellExecute "%TEMP%\%Admin_Name%_Start.bat", "", "", "runas", 1 >> "%TEMP%\%Admin_Name%__getPrivileges.vbs"
"%TEMP%\%Admin_Name%__getPrivileges.vbs"
endlocal
exit /B

:Administrator_OK
%$Parameters%
goto:eof
REM *** A D M I N I S T R A T O R  - Automatically get admin rights  (The End)  ***

History

This is the second version. Previously, after switching to administrator rights is not restored variables of the user's settings from its parent script.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here