Getting a list of all servers from your active directory is simple, and looks something like this :

dsquery

I wanted to get the list of servers (dc, sql1 & sql2).
In Powershell this can be done by splitting the line 3 times.

This looks like this :

@(dsquery computer -limit 0
      | %{$_.split("`"")[1]}
      | %{$_.split(",")[0]}
      | %{$_.split("=")[1]})

@ is used to call the dsquery process.
% is short for for-each

  • So, split on “  (the backtick is the escape character) and taking the second value from the resulting array is the first step and removes the quotes.
  • After that, split on , will break the line up in key/value pairs where only the first value from the array will be used (CN=…)
  • Finally split on the = and take the second value in the resulting array. This leaves you with a list of servers….

Want to filter out stuff ?

?{$_ -like '*OU=Servers*'}

use this after the first pipe symbol an pipe the results into the for-each statements.
The ? means where-object or where.
This example shows you only the OU’s named “Servers”.