How do I run a PowerShell script as administrator using a shortcut?
Asked Answered
H

1

6

I'm trying to run a PowerShell script as administrator using a shortcut. I have tried many ways, but it still does not work:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit -Verb RunAs Start-Process powershell.exe -ArgumentList '-file C:\project\test.ps1'

With this command, it will create two PowerShell windows and one window will close.

I also tried this one:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -NoExit Start-Process powershell.exe -Verb RunAs -File 'C:\project\test.ps1'

Can some one please help?

Henni answered 25/2, 2021 at 4:23 Comment(3)
I also tried this "powershell.exe -ExecutionPolicy Bypass -NoExit -File "C:\project\test.ps1" " I can run in normal way but cannot run as administrator, because when I run the administrator, it will go to the path of my Powershell not the project.Henni
https://mcmap.net/q/1775975/-launch-as-admin-powershell-via-batch-fileAdrianneadriano
If you just want to start powershell as admin it would be something like this powershell.exe -WindowStyle Hidden -command "& {start-process powershell -verb runas}"Adrianneadriano
A
7

Tl;dr

This will do the trick:

powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"

Explanation

First, you have to call PowerShell to be able to execute Start-Process. You don't need any additional paramters at this point, because you just use this first PowerShell to launch another one. You do it like this:

powershell.exe -Command "& {...}"

Inside the curly braces you can insert any script block. First you will retrieve your current working directory (CWD) to set it in the new launched PowerShell. Then you call PowerShell with Start-Process and add the -Verb RunAs parameter to elevate it:

$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList ...

Then you need to add all desired PowerShell parameters to the ArgumentList. In your case, these will be:

-ExecutionPolicy ByPass -NoExit -Command ...

Finally, you pass the commands that you want to execute to the -Command parameter. Basically, you want to call your script file. But before doing so, you will set your CWD to the previously retrieved directory and THEN call your script:

Set-Location $wd; C:\project\test.ps1

In total:

powershell.exe -Command "& {$wd = Get-Location; Start-Process powershell.exe -Verb RunAs -ArgumentList \"-ExecutionPolicy ByPass -NoExit -Command Set-Location $wd; C:\project\test.ps1\"}"
Apatetic answered 25/2, 2021 at 7:46 Comment(2)
Can you escape strings with \" or `" in Powershell?Burden
I found that I had to double-escape the quotes (backslash, backtick). I don't fully understand it, but this document was pretty good.Ahron

© 2022 - 2024 — McMap. All rights reserved.