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 -like
operator doesn't seem to work with wildcards for DistinguishedName. So the obvious operation Get-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,
# All the computers from the evil OU:
$evilOU = $computers| ? {$_.DistinguishedName -like "*ou=evil,*"}
# All the computers but the ones from the evil OU:
$goodOU = $computers| ? {$_.DistinguishedName -notlike "*ou=evil,*"}
Addendum
To combine matching rules, use -and
-or
and -like
. Remember to use *
wildcard with ? (where-object)
# All the computers save the ones from evil and wicked OU:
$goodOU = $computers| ? {
$_.DistinguishedName -notlike "*ou=evil,*" -and $_.DistinguishedName -notlike "*ou=wicked,*"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With