Windows – How to run batch file command with elevated permissions

batch filecommand linepermissionswindows

I am writing a batch file that I will distribute among users. I need to run some commands with elevated permissions. My initial solution was to use:

runas /noprofile /user:Administrator SOME_COMMAND  

However many machines (including mine) have the hidden Administrator account inactive and so do not have an administrator password set up. I can also not specify another user name since different machines will have different users. Is there a way to replicate the "right click -> Run as Administrator" action via a batch file? I do not mind the prompt popping up, I just do not want the user to explicitly right-click and run as administrator.

Best Answer

  • You can take advantage of PowerShell, which is present on every modern Windows system.

    Split the commands that need elevation off into a separate batch file, e.g. elevated.bat. Then, when it's time to run them, use this from your non-elevated script:

    powershell -command "Start-Process elevated.bat -Verb runas"
    

    The -Verb runas part is what causes the elevation prompt. If the original batch file is already running as admin, or if UAC prompts are off, the new file will be elevated without a prompt.

    Note that the elevated batch processor's current directory will start out as System32. If that's a problem, you can use this alternate version to have it start in the same directory as the non-elevated script:

    powershell -command "Start-Process cmd -ArgumentList '/c cd /d %CD% && elevated.bat' -Verb runas"
    

    That causes the new cmd instance to first cd into the directory provided by the unelevated prompt's %CD% variable, then execute the desired batch file.