Posts RSS Comments RSS 253 Posts and 393 Comments till now

blog: Avoid hardcoding in scripts. Here are some Simple discovery options in Powershell

When writing scripts I have always been a fan of making them as generic as possible. This may make the script a tad more complicated, but it allows it to be dynamic and also allows you to share these scripts between environments (i.e. Lab, QC, Production.) Basically we want to avoid hardcoding Domains, Domain Controllers, OUs, Containers, and site info.

Below I provide some simple examples of getting this information dynamically. This will allow you to discover the information instead of hardcoding it in the script.

To get forest information like Domains, Sites, ForestMode, RootDomain, and Forest masters you can use this:
  1. $Forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()

To get Domain information like Domain Controllers, DomainMode, Domain Masters, and Forest Root.
  1. $Domain = [DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

To get the current Site information for the local machine like Subnets, Sitelinks, Location, Bridgehead Servers, and Domain Controllers.
  1. $MySite = [DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()

With these variables you can find all the Active Directory infrastructure information you could possibly want.

Here are some more specific examples on how to use these variables:

To find all your Global Catalogs in the forest
  1. $Forest.GlobalCatalogs

To find all the Domain Controllers in the current domain
  1. $Domain.DomainControllers

To see what application partitions your forest has
  1. $forest.ApplicationPartitions

To see the forest roles
  1. $forest | select SchemaRoleOwner,NamingRoleOwner

To see the domain roles
  1. $domain | select PDCRoleOwner,RidRoleOwner,InfrastructureRoleOwner

To see the subnets in the current site
  1. $MySite.subnets

To see the bridgehead Servers
  1. $MySite.BridgeheadServers

Trackback this post | Feed on Comments to this post

Leave a Reply

You must be logged in to post a comment.