101

On my Windows 7 Desktop, I have script.ps1, which needs admin privileges (it starts a service). I want to click on this script and run it with admin privileges.

What's the easiest way to accomplish this?

Sajee
  • 6,059
  • 7
  • 26
  • 20

10 Answers10

86

Here is one way of doing it, with the help of an additional icon on your desktop. I guess you could move the script someone else if you wanted to only have a single icon on your desktop.

  1. Create a shortcut to your Powershell script on your desktop
  2. Right-click the shortcut and click Properties
  3. Click the Shortcut tab
  4. Click Advanced
  5. Select Run as Administrator

You can now run the script elevated by simple double-clicking the new shortcut on your desktop.

Kez
  • 16,631
  • 15
  • 67
  • 94
  • 85
    This worked for me, but **Run as Administrator** only became available after adding `powershell -f ` in front of the script path, so as to "complete" the command… – mousio Nov 01 '12 at 22:40
  • 2
    @mousio - I needed this too, thanks for the comment – m.edmondson Mar 18 '13 at 17:15
  • 3
    @mousio can you tell me why that command works? – SShaheen Aug 22 '14 at 12:54
  • 24
    @SShaheen - for **Run as Administrator** to become available, the shortcut needs to point to some sort of executable (e.g. powershell.exe) instead of just the document or script the shortcut originally pointed to. A shortcut to `script.ps1` works, as does a shortcut to `powershell.exe -f script.ps1`, but the latter can be set to run as administrator (see `powershell.exe /?` for the explanation of the `-f` or `-File` switch) – mousio Aug 22 '14 at 13:30
  • I use it to start the powershell console as administrator. A similar result is to create a ps1 file with `Start-Process powershell.exe -Verb RunAs`. – Timo Oct 29 '20 at 06:30
  • I don't get why this is upvoted when the shortcut has to point to the exe instead of the script. – clankill3r Dec 08 '20 at 20:35
51

On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script:

param([switch]$Elevated)

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

'running with full privileges'

Now, when running your script, it will call itself again and attempt to elevate privileges before running. The -elevated switch prevents it from repeating if something fails.

You may remove the -noexit switch if the terminal should automatically close when the script finishes.

xeruf
  • 170
  • 11
MDMoore313
  • 5,956
  • 1
  • 27
  • 31
  • If script requires arguments-parameters ? – Kiquenet Aug 29 '14 at 13:50
  • 1
    what if this tells me it is running with full privileges, but my code still says insufficient administrative privileges? – mike.b93 Mar 24 '17 at 18:12
  • 1
    @Kiquenet add it into the `param(...)` on top and forward them right before `-elevated`, you'll need to be clever about how you build the `ArgumentList`, probably will want to use the `String[]` form. – TWiStErRob Jan 11 '19 at 21:47
  • 2
    pretty nifty - better than creating a shortcut – Mikey Feb 06 '19 at 20:01
  • Thank you SO much, this has saved me! Little caveat: The "-noexit" flag may be nice for debugging, but perhaps undesired behavior in production... – xeruf Oct 18 '20 at 21:03
  • Can anyone please explain this code step by step ideally with the help of comments like we usually do in powershell files? I am not an expert and started learning ps recently. Thank you. I used the code and it worked fine. – user11702680 Aug 23 '22 at 15:58
  • @user11702680 I suggest you research each command and provide the comments as an update to the answer. I would gladly approve. – MDMoore313 Aug 27 '22 at 22:17
18

if you are in the same powershell you could do this:

Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"
mjsr
  • 6,438
  • 4
  • 29
  • 37
  • 1
    The problem with this is that it changes the working directory for the called script to `C:\Windows\System32`. An alternative which preserves the current directory: https://stackoverflow.com/a/57033941/2441655 – Venryx Jul 15 '19 at 06:35
4

Since it's sitting onto your desktop, I'd say the most effortless way to get this done is dragging it onto the elevation gadget.

Otherwise you could make a separate script using the elevate command on your ps1 script.

Or, you could apply elevate just to the service-starting bit.

badp
  • 3,667
  • 6
  • 40
  • 66
4

In addition to MDMoore313's answer above:

If we want to execute the commands in the same working directory as we are currently in, we have to add a few things:

#### START ELEVATE TO ADMIN #####
param(
    [Parameter(Mandatory=$false)]
    [switch]$shouldAssumeToBeElevated,

    [Parameter(Mandatory=$false)]
    [String]$workingDirOverride
)

# If parameter is not set, we are propably in non-admin execution. We set it to the current working directory so that
#  the working directory of the elevated execution of this script is the current working directory
if(-not($PSBoundParameters.ContainsKey('workingDirOverride')))
{
    $workingDirOverride = (Get-Location).Path
}

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# If we are in a non-admin execution. Execute this script as admin
if ((Test-Admin) -eq $false)  {
    if ($shouldAssumeToBeElevated) {
        Write-Output "Elevating did not work :("

    } else {
        #                                                         vvvvv add `-noexit` here for better debugging vvvvv 
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -shouldAssumeToBeElevated -workingDirOverride "{1}"' -f ($myinvocation.MyCommand.Definition, "$workingDirOverride"))
    }
    exit
}

Set-Location "$workingDirOverride"
##### END ELEVATE TO ADMIN #####

# Add actual commands to be executed in elevated mode here:
Write-Output "I get executed in an admin PowerShell"
1

PowerShell ISE lives at %windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe. You can right-click that and select "Run as administrator" and run the script from in there.

You can also find it under the Windows Logo > All Programs > Accessories > Windows PowerShell and do the same thing with those shortcuts.

vapcguy
  • 121
  • 4
0

If you want an option to launch a Powershell script as adminstrator, directly from the Explorer context-menu, see section 2 of my answer here: https://stackoverflow.com/a/57033941/2441655

Venryx
  • 316
  • 2
  • 8
0
sudo

Why does it have to take 30+ lines of code to do what 4 characters do?

So here, write a .bat file to invoke your script, in it use the:

Start-Process powershell.exe -Verb RunAs
Max
  • 21
  • 1
0

The previous answers only tells you if the script is running from an admin. If starting the same script with elevated privileges, the user is still not admin.

A parameter which can be used to determine this is the following :

if (($myinvocation.UnboundArguments.Contains("-elevated")) -or ($testadmin -eq $true)) {
   #Good to go with Admin rights

} else {
    #Start with elevated privs

}

I've not been able to find a parameter that detects the Powershell environment has been started with Admin privileges.

JFH
  • 1
  • 1
    Avoid posting answers to old questions that already have well received answers unless you have something substantial and new to add. – Toto Dec 22 '22 at 14:38
-1

Add this to the beginning of the script:

$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
Anthony
  • 9
  • 1