These are some useful little chunks of code I’ve cobbled together this past week for a variety of projects.  I hope they’re of use to you as well…

Check UAC Context

Test if PowerShell script is being executed via “Run as Administrator”

Function Test-RunAsAdmin {
  $myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
  if ($myWindowsPrincipal.IsInRole($adminRole)) {
    $result = $true
  Return $result

if (Test-RunAsAdmin) {
  Write-Host "You are running as Administrator"
else {
  Write-Host "You are NOT running as Administrator!"

Get an AD Site Name

Filter out an AD Site name from it’s LDAP distinguishedName in one statement (second line below).  You can drop this inside a loop, pipeline it, or make it a function.

$dn = "CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=contoso,DC=com"
$sn = ($dn.Split(",")[0]).Substring(3)

returns "Default-First-Site-Name"

Count Servers in an Active Directory domain

$qty = $(Get-ADComputer -LDAPFilter "(&(objectCategory=computer)(operatingSystem=*server*))").Length

Check if Domain Controller

Returns $true if the computer (either explicit or implicit/local) is a Domain Controller.

function Test-DomainController {
    [string] $ComputerName
  if ($ComputerName.Length -gt 1) {
    $cs = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $ComputerName 
  else {
    $cs = Get-WmiObject -Class Win32_ComputerSystem
  $role = ($cs).DomainRole
  if ($role -ge 5) {
    Return $True


function Test-DomainController {
  $cs = Get-WmiObject -Class Win32_ComputerSystem -Filter "DomainRole > 4"
  if ($cs -ne $null) {
    Return $True


There’s been some discussion regarding Get-CimInstance eventually taking over from Get-WmiObject.  However, I’ve noticed that it’s not quite a 1:1 yet, even in Windows 10 10547.  For example, if you grab a service within a collection iteration, such as Win32_Service, and try to invoke the .Delete() method, it’s there in Get-WmiObject, but not exposed via Get-CimInstance.  Small potatoes I’m sure, but it mattered in one situation for me recently.  Just thought I’d share that and see if anyone has some additional insights.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s