Link to home
Start Free TrialLog in
Avatar of David Sankovsky
David SankovskyFlag for Israel

asked on

recuresivley chack and create OUs

Hello Guys,
I need help with a PowerShell function that's part of a much larger script.
In general I'm building a script to automate AD user creation, and while there are several of those lying around.. non are as complete as I'm trying to make.
The current step has got me stumped.

Here's a short extract of my current script:
$Path = "C:\PSScript"
$CSVFile = $Path+"\userlist.csv"
$LogFile = $Path+"\usercreation.log.txt"
$Users = Import-Csv $CSVFile
foreach ($User in $Users){
        if ($user.OUCN) {
                $OUSearchString = "LDAP://"+$user.OUCN
                 if (-Not([adsi]::Exists($OUSearchString))){
                   ##NEED HELP HERE##
                  }
}

Open in new window

So basically, I was going to check if the OU in question exists in the AD and create it if not, but then It got me thinking, What if the OU in question is in Essence a Sub-OU and the part OU Doesn't exist either.

For Example, Lets Assume $user.OUCN returns "OU=Junior,OU=QA,OU=Software,OU=IL,DC=mydom,DC=local"
And only "OU=IL,DC=mydom,DC=local" exists in my AD.. In that case, will the following command:
New-ADOrganizationalUnit -Name Junior -Path "OU=QA,OU=Software,OU=IL,DC=mydom,DC=local" throw and error? or will it automatically create the parent OU(s) first.
If it's the latter, How can I build a PS function that will take an entire OUCN value and make sure it exists before I try to put a user into it?
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of David Sankovsky

ASKER

Check and verified to work,
A very good solution.
Thank you very much