Tuesday, February 8, 2011

Active Directory Forest Domain Controller Report using .Net

One of the nice features of PowerShell is the ability to leverage .Net. In the code sample below, I am able to export into a comma separated values text file a listing of all domain controllers in an Active Directory forest with some key information. Nowhere in the code am I specifying information about the root of the forest. Using the System.DirectoryServices.ActiveDirectory.Forest class, I am able to begin with a rich starting point to gather the information to describe the domain controllers in the forest of the security context of the account I execute the script.
Set-Variable -name forestInformation -option Constant -value ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest())
Set-Variable -name globalCatalogs -option Constant -value ($forestInformation.GlobalCatalogs | ForEach-Object { $_.Name })

$domainControllers = @()

foreach($domain in $forestInformation.Domains) {
 $domainName = (($domain.Name).Split(".")[0]).ToUpper()
 foreach($domainController in $domain.domainControllers | Sort-Object -property SiteName, Name) {
  $roles = @()
  if($globalCatalogs -contains $domainController.Name) {
   $roles += "Global Catalog"
  }
  if($domainController.Name -eq $domain.PdcRoleOwner){
   $roles += "PDC Emulator"
  }
  if($domainController.Name -eq $domain.RidRoleOwner){
   $roles += "Relative ID Master"
  }
  if($domainController.Name -eq $domain.InfrastructureRoleOwner){
   $roles += "Infrastructure Master"
  }
  if($domain.name -eq $forestInformation.RootDomain.Name -and $domainController.Name -eq $forestInformation.SchemaRoleOwner) {
   $roles += "Schema Master"
  }
  if($domain.name -eq $forestInformation.RootDomain.Name -and $domainController.Name -eq $forestInformation.NamingRoleOwner) {
   $roles += "Domain Naming Master"
  }

  $server = New-Object -typeName PSObject
  Add-Member -inputObject $server -type NoteProperty -name "domain" -value $domainName
  Add-Member -inputObject $server -type NoteProperty -name "fqdn" -value ($domainController.Name).ToLower()
  Add-Member -inputObject $server -type NoteProperty -name "ipAddress" -value $domainController.IPAddress
  Add-Member -inputObject $server -type NoteProperty -name "osVersion" -value $domainController.OSVersion
  Add-Member -inputObject $server -type NoteProperty -name "siteName" -value $domainController.SiteName
  Add-Member -inputObject $server -type NoteProperty -name "roles" -value ([System.String]::join(", ", $roles))
  $domainControllers += $server
 }
}

$domainControllers | Export-Csv -path ($forestInformation.RootDomain.Name + " Domain Controllers.csv") -noTypeInformation

No comments:

Post a Comment