Skip to content

Instantly share code, notes, and snippets.

@pcrockett-pathway
Last active June 13, 2019 12:34
Show Gist options
  • Select an option

  • Save pcrockett-pathway/51a732a116eb90be88c52cd743c96c61 to your computer and use it in GitHub Desktop.

Select an option

Save pcrockett-pathway/51a732a116eb90be88c52cd743c96c61 to your computer and use it in GitHub Desktop.
Self-elevating PowerShell script
[CmdletBinding()]
param()
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 5.0
$currentId = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = [Security.Principal.WindowsPrincipal]$currentId
$adminRole = [Security.Principal.WindowsBuiltInRole]"Administrator"
if (!$principal.IsInRole($adminRole)) {
# Not an admin. Re-run this script as administrator.
$scriptPath = $MyInvocation.MyCommand.Definition
$process = Start-Process "powershell.exe" `
-Verb "runas" `
-ArgumentList "-ExecutionPolicy", "RemoteSigned", $scriptPath `
-Wait `
-PassThru
if ($process.ExitCode -ne 0) {
throw "Admin PowerShell prompt exited with code $($process.ExitCode)."
}
return
}
"Congratulations, you're running in an admin PowerShell window!"
Pause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment