Thursday, May 24, 2018

Check Your Administrator Status in PowerShell

Most of the time, a script we've written for PowerShell may work like this:



 But then occasionally, this happens:



Whoops. What happened?

One thing to double-check is, Does our script require administrative access to work, and are we running PowerShell as an Administrator?

Here's how to check that:

([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")

 
The command is returning False, so no, this PowerShell instance was not launched as Administrator.

Of course, that's a long, hard-to-remember command, which means it's an excellent candidate for a function:

Function Check-Admin 
{  # Check Admin rights
([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")  
}  

 Stick that function into our profile, and we'll never have to remember that ugly command again.

No comments:

Post a Comment