Saturday, December 28, 2019

PowerShell: Automatic elevation of the script

Place this code at the beginning of your PowerShell script so that an elevation of privilege request is automatically issued:
 
#Elevate Credentials
param([switch]$Elevated)
function Check-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal `
$([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) }
if ((Check-Admin) -eq $false) {
    if ($elevated){
} else {
    Start-Process powershell.exe -Verb RunAs -ArgumentList `
 ('-noprofile -noexit -file "{0}" -elevated' -f ( $myinvocation.MyCommand.Definition ))
    } exit
}
#Start Main Script

No comments:

Post a Comment