Windows – Launch powershell as admin when double click on ps1 file

powershellwindows 10

I have read How to open a file for editing in Administrator mode?

I have a .ps1 file which needs to run as administrator. I'm happy to have it that when I double click on any .ps1 file, powershell runs as an admin.

I've gone to C:\Users\me\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell and made both the PowerShell shortcuts to run as admin

If I open Powershell from the start menu, I'm asked if I want to allow the app to make changes… This shows it's running as Admin, coupled with when Powershell is running it displays Administrator in the 'title' bar

However, when I double click on a .ps1 file, it opens as a normal user (not admin).

What else do I do need to do?

Best Answer

This will not execute the script when you double-click on it, but this will execute itself as elevated when you run it. You can try this:

$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    # code here...
}
else {
    Start-Process -FilePath "powershell" -ArgumentList "$('-File ""')$(Get-Location)$('\')$($MyInvocation.MyCommand.Name)$('""')" -Verb runAs
}

With this, the non-elevated console will exit.

Related Question