How to Get Domain Name Using PowerShell

Photo of author
By Jeff LeBlanc

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()
}

Local Computer

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

$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

Remote Computer

For a remote computer, you just need to add the -ComputerName parameter to the Get-WmiObject command.

Get-WmiObject -ComputerName <CompName> -Namespace root\cimv2 -Class Win32_ComputerSystem | Select Name, Domain

Hope this helps.

Happy Computing!

Leave a Comment