How can I run PowerShell as an administrator AND with arguments from a batch file?

It is possible to solve your problem without third-party tools, but the solution is somewhat arcane.

Therefore, consider downloading Bill Stewart's helpful elevate32 and elevate64 tools instead, as described in his answer, which simplifies the solution.

Here's a simple example that invokes the Get-Date cmdlet with arguments in an elevated PowerShell session launched from cmd.exe (or a batch file):

powershell -command "Start-Process -verb runas powershell" "'-noexit -command get-date -UFormat %s'"

Note how the command line to pass through to the elevated PowerShell session that the intermediary -command argument creates is passed as a single argument enclosed in embedded single quotes.

Quoting may get tricky, but this approach also works with invoking *.ps1 files in principle:

  • powershell -command "Start-Process -verb runas powershell" is the invariant part of the command line.

  • The remaining "..."-enclosed string must contain a nested single string with quoting that PowerShell recognizes (single quotes are easiest) containing all arguments that you would pass directly to a powershell ... command-line invocation.

Applied to your example:

... "'-File C:\path\to\filePath.ps1 arg1 arg2'"

Note: Be sure to use the full path to your script file, because the elevated PowerShell session does not (necessarily) run in the same directory as the calling session.

If you need to quote the arguments inside the nested string, use \":

... "'-File \"c:\path with spaces\to\filePath.ps1\" arg1 arg2'"

You can do this by grabbing a short command-line executable I wrote called Elevate32.exe (or Elevate64.exe for the 64-bit version). You can get it here:

http://www.westmesatech.com/misctools.html (ElevationToolkit1.zip)

Example:

elevate64 -- powershell.exe -file C:\scripts\myscriptfile.ps1

Everything after -- is the command line you want to elevate.