Query to filter specific OU's

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Jarkko Vepsäläinen Jarkko Vepsäläinen 1 week, 4 days ago.

  • Author
    Posts
  • #75085
    Profile photo of Ali Hassan
    Ali Hassan
    Participant

    Hi All,

    I am trying to run a GET-ADComputer cmdlet against certain OU's and what I want to do is exclude certain OU's from being scanned. Below is the code I have complied at the moment.

    $result = @()
    $ous = 'OU=Servers,OU=ACE3,OU=CH,OU=ACE,DC=contoso,DC=com','OU=Servers,OU=ACE4,OU=CH,OU=ACE,DC=contoso,DC=com'
    ForEach ($ou in $ous){
    $count = Get-ADComputer -Filter * -SearchBase $ou -Properties * | where{$_.operatingsystem -match 'Windows Server*'}   | select-object DNSHostName | Sort-Object DNSHostName -Descending
    $result+= $count
    }
    

    I need to exclude the below OU's from being scanned by the above cmdlet..

    OU=Backups,OU=IOU,OU=Servers,OU=ACE3,OU=CH,OU=ACE,DC=contoso,DC=com
    OU=Nonprod,OU=Mgt,OU=Servers,OU=ACE4,OU=CH,OU=ACE,DC=contoso,DC=com

    Any tips?

    -A

  • #75089
    Profile photo of Simon B
    Simon B
    Participant

    you could try filtering out the $_.DistinguishedName in your where clause something like :-

    where{(($_.operatingsystem -match 'Windows Server*') -and ($_.DistinguishedName -notlike "*OU=Backups,OU=IOU,OU=Servers,OU=ACE3,OU=CH,OU=ACE,DC=contoso,DC=com") -and ($_.DistinguishedName -notlike "*OU=Nonprod,OU=Mgt,OU=Servers,OU=ACE4,OU=CH,OU=ACE,DC=contoso,DC=com"))}

  • #75095

    Hi

    Hi

    Wouldn't it be faster to put those {(($_.operatingsystem -match 'Windows Server*') -and ($_.DistinguishedName -notlike "*OU=Backups,OU=IOU,OU=Servers,OU=ACE3,OU=CH,OU=ACE,DC=contoso,DC=com") -and ($_.DistinguishedName -notlike "*OU=Nonprod,OU=Mgt,OU=Servers,OU=ACE4,OU=CH,OU=ACE,DC=contoso,DC=com"))} into the -filter instead of where? Instead of first getting all computer objects and then selecting needed with where, just filter out only wanted in the first place.

    Also do not use wildcard in properties if you are selecting only DNSHostName. The wildcard is pulling everything from the object and then just limiting it to selected. It will be much faster just adding needed values to properties if needed more than the default gives to you. Also not a big fan of those += combinations..

    Regards

    Jarkko

You must be logged in to reply to this topic.