Run with elevated permissions

The CMD shell, START and RUNAS commands have no built-in options to elevate or run commands 'As Admin'

It is possible to right click CMD.exe (or it's Start menu shortcut) and run it As Admin.
Shortcuts can be edited to always run as Admin - Properties | Shortcut | Advanced then tick "Run as administrator".

To elevate from the command line will require running either VBScript or PowerShell, this does not have to involve completely rewriting existing scripts, you can use a couple of lines of either VBScript or PowerShell to launch an elevated CMD.exe and that will run a batch file elevated.

Another approach is to use a third party utility that will elevate permissions.

Testing for Elevation

Testing if the current session is elevated can be done with the FSUTIL command (via StackOverflow) or SFC.
Note that you don't even have to pass a drive letter to FSUTIL, it will set an errorlevel without reading any drive information.

fsutil dirty query >nul
If %errorLevel% NEQ 0 (
   Echo Failure, please rerun this script from an elevated command prompt. Exiting...
   Ping 127.0.0.1 3>&1 > nul
   Exit /B 1
) 
Echo Success: this script is running elevated.

When a script is run with elevated permissions several aspects of the user environment will change: The current directory, the current TEMP folder and any mapped drives will be disconnected.

Run without Elevation

In some cases you may wish to run an application without elevation, this will restrict what the application can do.

The undocumented environment variable __COMPAT_LAYER can be used to lower the ExecutionLevel to RunAsInvoker

@Echo Off
SETLOCAL
Set __COMPAT_LAYER=RunAsInvoker
regedit.exe

The example above will run REGEDIT using the user's native permissions, attempting to modify any protected area of the registry (such as HKLM) within this session will produce an error.

Scheduled Tasks

If a scheduled task invokes a UAC prompt, then the task will fail to run unattended, to prevent this make sure to select the 'Run With Highest Privileges' check box:

Elevate Scheduled task

“A man in public life expects to be sneered at – it is the fault of his elevated situation, and not of himself” ~ Charles Dickens

Related

UAC (User Account Control) - Disable or Limit popup prompts
PowerShell: Run with Elevated Permissions
VBScript: Run with Elevated Permissions
SS64 Forum thread on UAC detection.
elevate - Command-Line UAC Elevation Utility


Copyright © SS64.com 1999-2017
Some rights reserved