A quick utility function to add into your scripts to test whether or not PowerShell has been run as Administrator.
The function returns a boolean value ($True or $False).
1 2 3 4 5 6 7 8 |
function Test-IsAdmin { $CurrentIdentity = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent() $IsAdmin = $CurrentIdentity.IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator") Write-Output $IsAdmin } |
Example Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
if (Test-IsAdmin) { <# PowerShell is running as administrator. Crack on and do other scripty stuff. :) #> } else { <# PowerShell is NOT running as Administrator. Throw some useful error or warning, advising the users to run PowerShell again, but run as administrator. #> } |