The Computer Oracle

How to define a PowerShell function which requires elevation?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 How To Define A Powershell Function Which Requires Elevation?
00:48 Accepted Answer Score 44
01:42 Thank you

--

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

--

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