Skip to content

Instantly share code, notes, and snippets.

@bluPhy
Last active September 10, 2021 18:23
Show Gist options
  • Save bluPhy/763ba4f8a11db0183f167387e037f763 to your computer and use it in GitHub Desktop.
Save bluPhy/763ba4f8a11db0183f167387e037f763 to your computer and use it in GitHub Desktop.
Check if script is running as Administrator or with elevated privilege, if not use RunAs
function Use-RunAs {
# Check if script is running as Administrator or with elevated privilege, if not use RunAs
# Use Check Switch to check if admin
param([Switch]$Check)
# Detecting OS Platform, win32nt for Windows or unix for Linux/Unix
$OSPlatform = (([System.Environment]::OSVersion.Platform).ToString()).ToLower()
if ($OSPlatform -eq "unix") {
Write-Warning "Detected Linux/Unix OS, you don't need this, use sudo"
exit # Quit this session of powershell
}
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()`
).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if ($Check) { return $IsAdmin }
if ($MyInvocation.ScriptName -ne "") {
if (-not $IsAdmin) {
try {
# Detecting Powershell (powershell.exe) or Powershell Core (pwsh), will return true if Powershell Core (pwsh)
if ($IsCoreCLR) { $PowerShellCmdLine = "pwsh.exe" } else { $PowerShellCmdLine = "powershell.exe" }
$arg = "-file `"$($MyInvocation.ScriptName)`""
Start-Process "$PSHOME\$PowerShellCmdLine" -Verb Runas -ArgumentList $arg -ErrorAction 'stop'
}
catch {
Write-Warning "Error - Failed to restart script with runas"
break
}
exit # Quit this session of powershell
}
}
else {
Write-Warning "Error - Script must be saved as a .ps1 file first"
break
}
}
# Example
Use-RunAs
"Script Running As Administrator"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment