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?
LVL 9
David SankovskySenior SysAdminAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

oBdACommented:
Use this function; it requires the AD PS cmdlets.
Just pass it the DistinguishedName of the OU you want to create, and it will create the complete path (and return without error if the path already exists).
Function New-ADOrganizationalUnitRecurse([string]$DistinguishedName, [Switch]$PassThru) {
	$OUPath, $Parent = $DistinguishedName -split ',(?=\s*DC=)', 2 | ForEach-Object {$_.Trim()}
	$OUList = @($OUPath -split '(?:\A|,)\s*OU=' | Where-Object {$_})
	[array]::Reverse($OUList)
	Try {
		$OUList | ForEach-Object {
			$Name = $_
			Write-Host "Creating OU '$($Name)' in '$($Parent)' ..." -NoNewline
			Try {
				Get-ADOrganizationalUnit -Identity "OU=$($Name),$($Parent)" -ErrorAction Stop | Out-Null
				Write-Host " exists already."
			} Catch {
				$NewOU = New-ADOrganizationalUnit -Name $Name -Path $Parent -ErrorAction Stop -PassThru -ProtectedFromAccidentalDeletion $true
				Write-Host " OK."
				If ($PassThru) {
					$NewOU
				}
			}
			$Parent = "OU=$($Name),$($Parent)"
		}
	} Catch {
		Throw
	}
}

Open in new window


Sample call:
$Path = "C:\PSScript"
$CSVFile = $Path+"\userlist.csv"
$LogFile = $Path+"\usercreation.log.txt"
$Users = Import-Csv $CSVFile
ForEach ($user In $Users) {
	If ($user.OUCN) {
		New-ADOrganizationalUnitRecurse -DistinguishedName $user.OUCN
	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
David SankovskySenior SysAdminAuthor Commented:
Check and verified to work,
A very good solution.
Thank you very much
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.