Check if OU exists before creating it Check if OU exists before creating it powershell powershell

Check if OU exists before creating it


Simply check if Get-ADOrganizationalUnit returns an OU with that distinguished name and create it otherwise:

$parentOU = 'OU=parent,OU=PS,DC=example,DC=com'$navnpaaou = Read-Host "Type in the name of the new OU"$newOU = "OU=$navnpaaou,$parentOU"if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$newOU'") {  Write-Host "$newOU already exists."} else {  New-ADOrganizationalUnit -Name $navnpaaou -Path $parentOU}


I tried the accepted answer and found that it would throw an exception if the OU didn't already exist. The following function tries to retrieve an OU, catches the thrown error if it doesn't exist, and then creates the OU.

function CreateOU ([string]$name, [string]$path, [string]$description) {    $ouDN = "OU=$name,$path"    # Check if the OU exists    try {        Get-ADOrganizationalUnit -Identity $ouDN | Out-Null        Write-Verbose "OU '$ouDN' already exists."    }    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {        Write-Verbose "Creating new OU '$ouDN'"        New-ADOrganizationalUnit -Name $name -Path $path -Description $description    }}CreateOU -name "Groups" -path "DC=ad,DC=example,DC=com" -description "What a wonderful OU this is"