Official admin check for .bat and .cmd files

Discussion in 'Scripting' started by timesurfer, Aug 8, 2011.

  1. Compo

    Compo MDL Member

    Mar 29, 2011
    137
    108
    10
    You should receive an "ERROR: Access is denied." unless you are running Elevated. This error is output to STDERR, which is how we can catch it in the syntax I used.
     
  2. timesurfer

    timesurfer MDL Developer

    Nov 22, 2009
    8,527
    4,103
    270
    #22 timesurfer, Aug 15, 2011
    Last edited: Aug 15, 2011
    (OP)
    Worlds coolest batch admin check :worthy:

    Betcha everybody puts this in their batch's

    I have put your code demonstration in first post of batch repository

    Feel free to teach any level of batch coding and I'll put in that first post

    Thanks
     
  3. danyo1337

    danyo1337 MDL Junior Member

    Jul 24, 2010
    80
    7
    0
    #23 danyo1337, Aug 24, 2011
    Last edited by a moderator: Apr 20, 2017
    I found this snippet a while back in a script that allows concurrent remote desktop sessions and changed it a bit.

    Code:
    SET HasAdminRights=0
    FOR /F %%i IN ('WHOAMI /PRIV /NH') DO (
    IF "%%i"=="SeTakeOwnershipPrivilege" SET HasAdminRights=1
    )
    
    IF NOT %HasAdminRights%==1 (
    "%~dp0Error.vbs"
    EXIT
    )
    Error.vbs
    Code:
    MsgBox "This script must be run with Administrator privileges!", 16, "Error!"
     
  4. racky29

    racky29 MDL Senior Member

    Aug 2, 2007
    285
    92
    10
    #24 racky29, Apr 1, 2012
    Last edited by a moderator: Apr 20, 2017
    batch file auto admin uac prompt

    found this script to give automatic elevated admin privilege

    Code:
    
    @Echo off
    :: Check for permissions
    >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
    
    :: If error flag set, we do not have admin.
    if '%errorlevel%' NEQ '0' (
    Echo Requesting administrative privileges...
    goto UACPrompt
    ) else ( goto gotAdmin )
    
    :UACPrompt
    Echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    Echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
    
    "%temp%\getadmin.vbs"
    Exit /B
    
    :gotAdmin
    if exist "%temp%\getadmin.vbs" ( Del "%temp%\getadmin.vbs" )
    Pushd "%CD%"
    CD /D "%~dp0"
    
    REM <YOUR BATCH SCRIPT HERE>
    ECHO.
    ECHO You should have had a UAC Prompt
    ECHO and now you have Admin Rights
    ECHO.
    pause
    
    
    copy that code to a txt file and name it testadmin.cmd
    and run it

    got it from here, http://ss64.com/nt/runas.html