[CmdletBinding()]
Param(
[Parameter(Mandatory=$false)]
[switch]$RunElevated
)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($RunElevated) {
Write-Warning 'We tried to elevate and failed'
} else {
try {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -nologo -noexit -file "{0}" -RunElevated' -f ($myinvocation.MyCommand.Definition)) -EA Stop
} catch {
Write-Warning ('Error trying to self-elevate: {0}' -f $_.Exception.Message)
}
exit
}
}
Write-Host "Hello elevated world!"
# Code that needs elevation