Last active 4 months ago

This script ensures that it runs with administrator privileges before executing the actual code. If no admin rights are available, it restarts itself with elevated privileges.

Revision 2afdd153befd7d1b199d9d7b5699733a2b9d0541

ElevatedPowershellExample.ps1 Raw
1param([switch]$Elevated)
2
3function Test-Admin {
4 $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
5 $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
6}
7
8if ((Test-Admin) -eq $false) {
9 if ($elevated) {
10 # tried to elevate, did not work, aborting
11 } else {
12 Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
13 }
14 exit
15}
16
17'test'