Run Multiple Commands As Admin From PS1 File ( Windows Terminal)

powershellrunaswindowswindows-terminal

This PS1 File (test.ps1), while executed, will run The Commands Pushd $Home; bcdedit /enum bootmgr; pause As Admin in PWSH.exe its self.

# test.ps1
$AL = "-NoProfile -WindowStyle Maximized -ExecutionPolicy Bypass", 
      "-Command", "Pushd $Home; bcdedit /enum bootmgr; pause"
Start -Verb RunAs -FilePath pwsh.exe -ArgumentList $AL

What is the writing format, if I execute it (test.ps1), then will opened in Windows Terminal Elevated/ As Admin?

I tried:

# test.ps1
$AL = "-M -p 'PowerShell'", 
      "pwsh.exe -ExecutionPolicy Bypass -Command `"Pushd $Home; bcdedit /enum bootmgr; pause`""
Start -Verb RunAs -FilePath wt.exe -ArgumentList $AL

giving the errors:

[error 2147942402 (0x80070002) when launching `" pause"']

[error 2147942402 (0x80070002) when launching `" bcdedit /enum bootmgr"']

I have also tried other formats but the error still persists.

Only works if one command:

# test.ps1
$AL = "-M -p 'PowerShell'", 
      "pwsh.exe -ExecutionPolicy Bypass -Command `"bcdedit /enum bootmgr`""
Start -Verb RunAs -FilePath wt.exe -ArgumentList $AL

Best Answer

Unescaped ; on the wt.exe command line serve to separate multiple commands for Windows Terminal.

Therefore, ; characters to be passed through to a target executable must be escaped, namely as \;, which is unfortunately always necessary - even for ; characters inside (embedded) "...".

  • As of this writing, the linked documentation doesn't state this requirement; GitHub docs issue #763 aims to correct that.

Therefore:

$AL = "-M -p PowerShell -d `"$HOME`" " + 
      'pwsh.exe -ExecutionPolicy Bypass -c "bcdedit /enum bootmgr\; pause"'
Start-Process -Verb RunAs -FilePath wt.exe -ArgumentList $AL

Note:

  • For simplicity, the above uses wt.exe's -d option to pass a startup directory.
  • A single string encoding all arguments is passed to the -ArgumentList parameter, which is generally preferable to work around a long-standing bug that won't be fixed - see this SO answer.
Related Question