How to Get Domain Name Using PowerShell

For large Enterprise environments it is common to have 3 separate Domains and SCCM environments. One for DEV, one for UAT testing and then Production.

Sometimes it can be helpful when writing scripts to check which environment we are functioning within and then use values for server names or Site Codes based on the environment.  This allows us to use the same script in all 3 environments without having to specify different script parameters.

While there are definitely cases where taking the SiteCode or SiteServer values via command line parameters makes more sense, for some automation scripts, it is just easier to handle things for all 3 environments based on the Domain and go from there.

The following is a simple Function for getting Domain information for a computer.

Function Get-Domain {
   $CompInfo = Get-WmiObject -Namespace root\cimv2 -Class Win32_ComputerSystem | Select Name, Domain
   Return $CompInfo.Domain.ToUpper()
}

Usage:

$Domain = Get-Domain

Switch ($Domain) {
   DEV.COM {
      $CASSiteCode = "CAD"
      $CASSiteServer = "<FQDNYourServerName>"
   }
   UAT.COM {
      $CASSiteCode = "CAU"
      $CASSiteServer = "<FQDNYourServerName>"
   }
   PROD.COM {
      $CASSiteCode = "CAS"
      $CASSiteServer = "<FQDNYourServerName>"
   }
   default {
      Write-Host "No supported Domain found. Exiting script." -ForegroundColor Red
      Exit(-1)
   }
}

# Do More Stuff

Leave a Comment