5

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?

3
  • you could include something like if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) -eq $false){Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass" -Verb RunAs; Exit;} in your $Profile - however, for some reason, Exit does not work, therefore the original non-admin terminal will stay open... (you could also include that script in a slightly modified version in each script that need admin privileges.)
    – flolilo
    Feb 8, 2018 at 16:11
  • winaerotweaker allows you to run ps1 files as admin Feb 8, 2018 at 16:30
  • I know a registry script which add context menu to run powershell script as administrator.
    – Biswapriyo
    Feb 8, 2018 at 17:31

4 Answers 4

5

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.

1

Copy/paste your powershell shortcut to a place where you would like to launch the script from. Right-click the new shortcut, click properties, and then advanced and make sure it's set to run as administrator. Then, in the in the target box type the path to and name of the script after powershell.exe

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe c:\myscripts\my-awesome-script.ps1

Make sure you use "quotes" around your addition if there are any spaces in the path or filename like:

"c:\my scripts\some script with spaces.ps1"

This will launch a new powershell as an administrator and start the script automatically in the new shell.

You'll probably also want to rename the shortcut to indicate that it's for a specific script, instead of a regular powershell session. Right-click, rename.

2
  • When you add the shortcut to your powershell script, the target of the shortcut will just be the script file, you need to edit the Target box and put powershell.exe -f before the file name, ie: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -f C:\Users\Joe\Desktop\scripts\myScript.ps1 Mar 16, 2021 at 0:03
  • After you do that, ONLY THEN can you change the shortcut to run as admin, ie Advanced button-> Run as administrator Mar 16, 2021 at 0:05
1

I ended up having to resort to a commercial software package for this due to the difficulties Microsoft puts in the way of those who want their PowerShell scripts to run like batch files (double-click and it just runs)

My script:

  • Needs to run as administrator
  • …after being double-clicked, a UAC prompt is fine
  • …regardless of the execution policy currently in place

The answer given above does work for making a script run as administrator, but the code required for doing so is both ugly, and doesn't address the execution policy problem (the script will just immediately fail). It also doesn't make the script double-clickable.

The other answer given will make the script double-clickable and have it run as administrator, but would be unsuitable for anything but a script that is being more or less "installed" on a system for regular use, and requires a lot of manual steps. It does not address the execution policy problem either, although it could since PowerShell is being invoked we could pass -executionpolicy bypass as a option

There are other (free) tools out there that will "package" a PowerShell script into an EXE file like PS2EXE which neatly solved the double-clicking problem, but what I found is that this does not play well with the "run as admin" code given in the answer here, neither does it work around the execution policy.

I ended up going with PowerShell studio since it offers the same "packaging" ability that PS2EXE has, you can set a flag to force the EXE to run as admin (so no need for littering your script with escalation code), it executes the script with the bypass flag so you don't get stopped in your tracks or have to care what the local policy is set to, and perhaps most helpfully, has tools to "sign" the resulting package so that your user doesn't get scary warnings.

This is, so far, the only way I've found to reliably distribute a PowerShell script that requires admin permissions.

1
  • This is the best answer imo. PS2EXE does have a -requireAdmin flag btw, you won't need PowerShell Studio. Jun 12, 2023 at 7:06
-2

Explanation

Windows don't allow PowerShell script to run natively, you need to update the execution policy for your user or a selected user to use them.

Answer

  1. Open your PowerShell (In admin mode if needed)
  2. Change the execution policy Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
  3. Type Get-Execution -List to see all execution policy

            Scope    ExecutionPolicy
            -----    ---------------
    MachinePolicy    Unrestricted
    UserPolicy          Undefined
    Process             Undefined
    CurrentUser      RemoteSigned
    LocalMachine     Unrestricted
    

If this still doesn't work you can use Windows PowerShell ISE which is the PowerShell IDE

  1. Right-click on your *.ps1 file
  2. Open With → Windows PowerShell ISE

Or simply open ISE first.

Security

Microsoft doesn't allow you to run PowerShell script by default for serious security reason, someone could easily run a script on your computer and have full access! To avoid that please set your execution policy back to what they were.

Microsoft documentation

2
  • execution policy: docs.microsoft.com/en-us/powershell/module/…. The execution policy isn't a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.
    – Paul Fijma
    Apr 13, 2021 at 13:25
  • The execution policy has absolutely nothing to do with the double-click behavior.
    – Karu
    Mar 8, 2023 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .