When I first started using PowerShell I was both amazed and frustrated. One of my first projects required that I generate a list of all the users in my company’s large Active Directory forest. I figured out the Get-ADuser part in no time but was disappointed to see the returns from my commands only listing the users from the domain I was currently logged in to. We had 20 plus child domains at the time. Where was the -alldomains parameter for the command?

Here’s what I came up with. Using the Get-ADForest cmdlet I could get a list of all the domains but it still wasn’t something I could plug into any Get-ADuser parameters. I figured out that I could also use Get-ADDomainController -DomainName to find a DC and that Get-ADuser had a -server paramater. I was soooo close. I just need to put them all together.

Import-Module ActiveDirectory
$domains = (Get-ADForest).domains
$dcs = ForEach ($domain in $domains) {Get-ADDomainController -DomainName $domain -Discover -Service PrimaryDC | Select -ExpandProperty hostname}

This string of commands (small script) results in the $domain variable containing a list of all the primary domain controllers in an AD Forest. Now we can use that variable with the -server parameter and get our list:

$AllUsersReport = ForEach ($dc in $dcs) {Get-ADUser -server $dc -properties *}
$AllUsersReport|Export-Csv - path c:\temp\allusersreport.csv -notypeinformation

We’ll end up with a nice CSV file conaining all the details of every user in our Forest. I have used the  top part (getting the domain controllers) in countless scripts since. For examaple:

Import-Module ActiveDirectory
$dcs = foreach ($domain in $domains) {Get-ADDomainController -DomainName $domain -Discover -Service PrimaryDC|select -ExpandProperty hostname}

$systems = foreach ($dc in $dcs) {Get-ADComputer -properties * -Filter {(OperatingSystem -like "*Windows*") -and (OperatingSystem -NotLike "*Server*")} -Server $domain |select DNSHostName, IPv4address, OperatingSystem, OperatingsystemServicePack, LastLogonDate

The scirpt above will output a Grid of all the Windows workstation computers in your entire forest. A quick change of (OperatingSystem -NotLike “*Server*”) to (OperatingSystem -Like “*Server*) will output a grid of all your servers.