20

Since I can't find any alternative to Linux' sudo elevation command, I have the following question:

How to define a PowerShell function which requires elevation? I mean UAC prompt.

Say, such function follows:

function system-check {
    SFC /ScanNow
}

System:

Windows 8.1 Pro 64-bit

PowerShell:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  117

EDIT1:

To be 100% understandable let me rephrase:

  1. I run PowerShell as user
  2. I run the aforementioned function system-check
  3. I want the function to elevate in order to be able to execute the command; note, that I want the UAC prompt to appear
  • Note that many built in powershell commands and commands added by Microsoft modules (such as MSOL commands) often require elevation but in no way provide assistance in privilege elevation. They simply fail with cryptic error messages. If you build an elevation prompt into your scripts, you'll be providing more user friendliness than Microsoft themselves. – Todd Wilcox Aug 11 '17 at 12:22
32

To run a specific command from an elevated window:

Start-Process -FilePath powershell.exe -ArgumentList {$ScriptBlock} -verb RunAs

For example:

Start-Process -FilePath powershell.exe -ArgumentList {
    SFC /scannow
} -verb RunAs

To run a specific script from an elevated window:

Start-Process powershell -ArgumentList '-noprofile -file MyScript.ps1' -verb RunAs

To run an entire PowerShell session prompting for UAC:

Start-Process powershell.exe -Verb runAs

A function to return $True or $False if the current window is running with elevated permissions:

function isadmin
 {
 #Returns true/false
   ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
 }

To ensure a script is only run As Admin, add this to the beginning:

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
 {
  Echo "This script needs to be run As Admin"
  Break
 }

In PowerShell v4.0 the above can be simplified by using a #Requires statement:

#Requires -RunAsAdministrator

Source: Run with elevated permissions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.