The Computer Oracle

How to define a PowerShell function which requires elevation?

--------------------------------------------------
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow

--

Chapters
00:00 Question
01:09 Accepted answer (Score 42)
02:25 Thank you

--

Full question
https://superuser.com/questions/1239791/...

Question links:
[sudo]: https://en.wikipedia.org/wiki/Sudo

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#powershell #uac

#avk47



ACCEPTED ANSWER

Score 44


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