Powershell - Filtering OUs while using get-adcomputer

我怕爱的太早我们不能终老 提交于 2019-12-01 17:21:40

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,*"

}

while there's nothing wrong with filtering after you've collected all the computers, a more efficient manner of restricting your data to one OU would be to use the -searchbase switch in your GET-ADCOMPUTER cmdlt. I also noticed you're filtering your object type to specify computer, which is a little redundant as the get-adcomputer cmdlt already filters out other object types.

i've taken your code and fixed it up a bit.

import-module ActiveDirectory
$computers = get-adcomputer -Filter * -properties "OperatingSystem" -SearchBase "OU=evil,OU=workstations,DC=cs,DC=domain,DC=net"
$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"

The above above example should function the same as your previous scrip save that it will enumerate all the computers with either windows 7 or xp that are within the evil OU. which is located within the workstations OU on the ds.Domain.Net domain.

You've probably also noticed that your distinguished name is getting ".DistinguishedName" appended to the end of each column, this is because your $computer.DistinguishedName expression isn't being fully evaluated while it's in quotations, easily resolved with the following change:

"$computer.DistinguishedName"

to

"$($computer.DistinguishedName)"

the "$(<...>)" syntax tells powershell to evaluate the full expression within brackets before converting the output to string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!