0

If I run this it returns properly:

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer) (cn=*dc*))'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }

If I run it with two selections it fails:

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer) (cn=*dc*) (cn=*adm*))'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }

If I run it with an OR instead, it returns all Computers:

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(|(objectClass=Computer) (cn=*dc*) (cn=*adm*))'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }

What am I missing in the Filter part in order to search on just two wildcard names? BTW, it seems to work fine if I am trying to exclude computers:

$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer)(!(cn=*esx*)) (!(cn=*slng*)) (!(cn=*dcen*)) )'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }
onefiscus
  • 129
  • 1
  • 3
  • 15

2 Answers2

2

I found a cleaner method for doing this:

Get-ADComputer -Filter { Name -like '*dc*' -or Name -like '*adm*'} | sort-object Name | select-object -ExpandProperty Name `
| Out-File -FilePath C:\Scripts\PI_Computers.txt

Thanks!

onefiscus
  • 129
  • 1
  • 3
  • 15
1

Just for the protocol:

The correct LDAP-Filter for your query is

(&(objectClass=Computer)(|(cn=*dc*)(cn=*adm*)))

But your solution is the better one (It is always better to use the predefined Cmdlets for default-tasks)

Bye

Ronny Kaufmann
  • 446
  • 2
  • 7