Search code examples
windowspowershellbatch-filecmdpowershell-4.0

Open powershell as an administrator and run commands in powershell using bat file


I am doing a powershell task manually i.e. opening the powershell as an administrator and executing the command pushd D:\PowerShellTry and command .\FileWatcher.ps1 in powershell.

I wrote a myScript.bat to automate the manual task through a bat file. Below is the code which I wrote for my bat file to automate it:

powershell -Command "& {Start-Process powershell.exe -Verb RunAs; pushd D:\PowerShellTry; .\FileWatcher.ps1}"

But it is not working. How can I do this correctly?


Solution

  • powershell -Command "Start-Process -Verb RunAs powershell.exe '-NoExit pushd D:\PowerShellTry; .\FileWatcher.ps1'"
    

    Note the use of embedded '...' quoting and the -NoExit switch to keep the elevated session open, so you can examine the script's output.

    As for what you tried:

    • Note that here's no reason to use "& { ... }" in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use "..." directly, as shown above.
      (Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected.)

    • By placing ; after Start-Process powershell.exe -Verb RunAs, you terminated the command right there, launching an interactive elevated PowerShell session asynchronously; the subsequent pushd ...; .\... commands then executed in the original, non-elevated session.

      • Instead, the commands to be run with elevation must be passed as arguments to the powershell.exe instance launched with -Verb Runas, as shown above, just like with the outer powershell.exe call (the -Command CLI parameter is implied, as is Start-Process' -ArgumentList parameter).