Getting a list of all servers from your active directory is simple, and looks something like this :
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”.
Filed under:
RoboDBA

[...] created a list of servers for him to scan using this method) Filed under: [...]
Another way of handling this is with Regular Expressions (which are extremely powerful, once you get the hang of them).
@(dsquery computer -limit 0 | %{[regex]::Replace($_, “`”CN=([^,]+),.*$”, ‘$1 ‘)})
This uses the .Net Regex object’s Replace method. I won’t repeat what is said above. But the regular expression is “`”CN=([^,]+),.*$”.
Breaking it into pieces we have
`” An escaped quote, so this matches the quote
CN= A literal string, so this matches the string CN=
(…) The stuff between the parens is a CAPTURED and will be stored in the $1
[^,] Match anything but the comma
+ Do the previous match (the [^,]) one or more times.
, A literal string, so this matches the comma
. Match any character
* Do the previous match (the any character) zero or more times
$ Match the end of the string.
So, what this regex does is throw away the “CN= at the beginning of the string and also everything after the comma. The stuff between the CN= and the comma is stored in the capture.
The Replace then takes the incoming string and replaces it with what was captured in the $1.