Create missing objects in complex OU structure

Create an object in a complex OU structure if not already present.

John Savill

May 20, 2017

1 Min Read
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 while I wanted each to have an account named 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 LABforeach ($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"        }        else        {            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"        }    }}

 

About the Author

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like