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 8
David SankovskySenior SysAdminAsked:
Who is Participating?
 
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
 
David SankovskySenior SysAdminAuthor Commented:
Check and verified to work,
A very good solution.
Thank you very much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.