• 512-991-7197
  • This email address is being protected from spambots. You need JavaScript enabled to view it.
  • Always Open

Welcome to Active Directory Tips & Tricks

Create missing objects in complex OU structure

Create missing objects in complex OU structure

Star InactiveStar InactiveStar InactiveStar InactiveStar Inactive

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"

Recommend other relevant articles:

Every master document consists of a normal document stuff and links to other documents. Those links can be used



© 2019 Austin Laptop [AustinLaptop.Com]. All Rights Reserved.