How to define a PowerShell function which requires elevation

powershelluac

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

Best Answer

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

Related Question