Search through multiple OUs in the AD with PowerShell

###
#
# Get every computer / user object from the given OUs of the AD to which the filters apply
# 
# The results will be sorted!
#
###


# the following is an example how to search for servers and domain controllers in specific OUs
# it shows only results with DistiguishedNames NOT containing certain words!
$OUs = 'OU=SERVER,OU=LOCATIONNAME,DC=EXAMPLE,DC=COM', 'OU=DC,OU=LOCATIONNAME,DC=EXAMPLE,DC=COM'

$comp = $OUs | ForEach-Object {Get-ADComputer -Filter * -SearchBase $PSItem | Where-Object {   ($_.DistinguishedName.Contains("whatever") -eq $false)   -and   ($_.DistinguishedName.Contains("anothertext") -eq $false)   } } | Sort-Object Name

Write-Host $comp.Count



# Another example

# we want to find here every user from these two OUs who is not disabled and whose company field contains specific words

$OUs = 'OU=Users,OU=LOCATIONNAME,DC=EXAMPLE,DC=COM', 'OU=IT,OU=Users,OU=LOCATIONNAME,DC=EXAMPLE,DC=COM'

$temp = $OUs | ForEach-Object {Get-ADUser -Filter * -SearchBase $PSItem -Properties Enabled, Company, DisplayName, EmailAddress, Department | Where-Object {   ($_.Enabled -eq $true)   -and   (($_.Company.Contains("something") -eq $true)   -or   ($_.Company.Contains("someimportantstring") -eq $true))   } } | Select-Object DisplayName, EmailAddress, Department | Sort-Object DisplayName

$temp | Export-Csv "C:\Temp\Test.csv" -NoTypeInformation -Delimiter ";" -Encoding UTF8
PowerShell

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *