简体   繁体   中英

Exporting users from specific OUs

I'm writing a PowerShell script to list of all our users in our active directory. Within our main OU we have sub OUs, there are two things i'm struggling with.

First being I need to exclude specific sub OUs from this report I'm not sure how to do this. The second problem I am having is i'd like to have the OU they are within included within the report, at the moment I get a output like this:

DisplayName   CanonicalName

Kanye West    ad.test/All Users/People that have left/Kanye West

I'd to exclude the "ad.test/All users" and "/Kanye west". So all I'd like to output is the SUB OU name.

Here is what I have written so far:

Get-ADUser -Filter * -SearchBase "OU=All Users, DC=ad,DC=test" -Properties DisplayName, CanonicalName | select DisplayName, CanonicalName | Export-CSV c:\experiment.csv

If you only need the output from one OU, I'd suggest going to that location first.

Import-Module activedirectory
Set-Location 'AD:\OU=People that have left,OU=All Users,DC=ad,DC=test'
Get-ADUser -Filter * -Properties DisplayName,CanonicalName | Select-Object DisplayName,CanonicalName | Where-Object CanonicalName -ne 'Kanye West' | Export-CSV C:\Experiment.csv

Add:

Import-Module activedirectory
Get-ADUser -Filter 'CanonicalName -ne "Kanye West"' -SearchBase 'OU=People that have left,OU=All Users,DC=ad,DC=test' -Properties DisplayName,CanonicalName |
  Select-Object DisplayName,CanonicalName |
  Export-CSV C:\Experiment.csv

Not sure if this is exactly what you are looking for but I would get a list of all OU's/Containers you want to search first in an array and then search all of those for objects.

# The OU you want to start searching from
$baseOU = "OU=All Users, DC=ad,DC=test"
# Any OUs that you do not want to be searched
$ouOmits = "All users","Kanye West"
# Get all sub OUs and OU of $baseOU minus any OU that is in the omission list
$ousToSearch = Get-ADOrganizationalUnit -SearchBase $baseOU -Filter *  | 
    Where-Object{$_.name -notin $ouOmits} | 
    Select -Expand DistinguishedName

If you only have PowerShell 2.0

$ousToSearch = Get-ADOrganizationalUnit -SearchBase $baseOU -Filter *  | 
    Where-Object{$ouOmits -notcontains $_.name} | 
    Select -Expand DistinguishedName

So that will get all OU's you want to search for. So now lets loops through them and get all of the objects we actually want.

$ousToSearch | ForEach-Object{
    Get-ADUser -Filter * -SearchBase $_ -SearchScope OneLevel -Properties DisplayName,CanonicalName
}

Normally the search is recursive. To make sure our omits work as intended then we limit the search to just the OU's we are asking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM