Snippet #1 – Checking for Admin Rights with PowerShell

I know we’ve all been rather slack with the blog lately, this post is a more concerted effort by me to resolve this!

As a die-hard VBScript-er I never really saw the need for me to learn Microsoft PowerShell… until I was required to use it to conform to the coding standards on a project I was working on. Well I get it now, it works and is immensely powerful.  Also, why write 20 lines of VBS when you can achieve the same with a single line of PowerShell? It works a treat, although I still drop back to VBS from time to time 🙂

Over time I’ll share code snippets that I use frequently that could prove useful to the masses, even if it is just to show the simplicity of something in PowerShell. The first snippet I’m sharing is how to check if your script is running with admin rights or not.

Add it as a function to your script, it will then return a Boolean value back to your caller.

$boolAdminRights = funcCheckAdminRights
Write-Host $boolAdminRights

Function funcCheckAdminRights
{
$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal = new-object ‘System.Security.Principal.WindowsPrincipal’ $windowsIdentity
$AdminRights = $windowsPrincipal.IsInRole(“Administrators”)

If ($AdminRights)
{
# Admin rights OK
Return $True
}
Else
{
# No admin rights
Return $False
}
}

Pretty simple!

Advertisements