I am trying to create a script that generates a list of computers based on specific properties which a computer may have. For example, I am trying to make a list of Windows XP computers and Windows 7 computers, throw their names in a .csv file and outputting the final count of each.
Here is my code so far
import-module ActiveDirectory
$computers = get-adcomputer -Filter 'ObjectClass -eq "Computer"' -properties "OperatingSystem"
$i = 0
$j = 0
Foreach ($computer in $computers) {
if ($computer.operatingSystem -like "Windows 7*") {
$i++
'"{0}","{1}","{2}"' -f $computer.Name, $computer.OperatingSystem, "$computer.DistinguishedName" | Out-file -append C:\users\admin\desktop\test.txt
}
elseif ($computer.OperatingSystem -like "Windows XP*") {
$j++
'"{0}","{1}","{2}"' -f $computer.Name, $computer.OperatingSystem, "$computer.DistinguishedName" | Out-file -append C:\users\admin\desktop\test.txt
}
else {
$_
}
}
write-host "$i Win 7"
write-host "$j Win xp"
$k = $i+$j
write-host "$k Total"
Sample Output:
104 Win 7
86 Win xp
190 Total
This script works however I would like to make it a bit better by being able to say which OU’s not to look into, but I can’t quite figure it out.
If anyone has any insight into how to do this, or even just to make the above code any better I would love to hear it.
Thank you!
The
-likeoperator doesn’t seem to work with wildcards for DistinguishedName. So the obvious operationGet-ADComputer -Filter {(DistinguishedName -notlike "*OU=evil,*")}doesn’t work.The easiest workaround is to get all the computers in a colleciton and filter it afterwards to suit your needs. Like so,
Addendum
To combine matching rules, use
-and-orand-like. Remember to use*wildcard with? (where-object)}