Create missing objects in complex OU structure

Create missing objects in complex OU structure

Q. What is some sample PowerShell to search for a certain user account in a complex OU structure and if not present create it?

A. I had a global OU structure where each Lab required a certain account. I had a number of geographical region OUs and then within those each LAB had an OU with a child OU named Users. The each Lab was named LAB<location> while I wanted each to have an account named <location>EXP-ECHUB. Some regions already had the account so the code had to check if the account already existed and if it did not exist then create it (using a separate cmdlet that already existed but you could replace with a simple New-ADUser command). Note I search each top level OU for other OUs only one level under.

$RootDomain = "DC=savilltech,DC=net"

$TopLevelLABs = "APAC","EMEA","NA","SA"

#Find each LAB
foreach ($TopLevelLAB in $TopLevelLABs)
    #Find the child OUs
    $LABs = Get-ADOrganizationalUnit -SearchBase "OU=$TopLevelLAB,$RootDomain" -filter * -SearchScope OneLevel

    #Look for each LAB
    foreach ($LAB in $LABs)
        $ECHUB = $null
        #Checking for a Hub account
        $ECHUB = get-aduser -SearchBase "OU=Users,$($LAB.DistinguishedName)" -Filter {name -like '*ECHUB'}
        if($ECHUB -ne $null)
            Write-Output "$($LAB.Name) has account already"
            Write-Output "*** $($LAB.Name) needs an account so creating ***"
            $HubFirstName = $LAB.Name.Replace("LAB","") + "EXP"
            Write-Output "*** Creating $HubFirstName-ECHUB ***"
            New-OneLABSpecUser $HubFirstName ECHUB $($LAB.Name) "Hub Account"


Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.