Freshman
Freshman

Reputation: 303

Check if OU exists before creating it

function NyChildOU {
  $overOU = Read-Host "Type in the name of the parrent OU"
  $oucheck = [adsi]::Exists("LDAP://OU=$overOU,OU=PS,DC=PS,DC=local")
  if ($oucheck -eq "true") {
    $navnpaaou = Read-Host "Type in the name of the new OU"
    $oucheck2 = [adsi]::Exists("LDAP://OU=$navnpaaou,OU=$overOU,OU=PS,DC=PS,DC=local")
    if ($oucheck2 -eq "false") {
      New-ADOrganizationalUnit -Name $navnpaaou -path "OU=$navnpaaou,OU=$overOU,OU=PS,DC=PS,DC=Local"
      Write-Host "The new entry: $navnpaaou is created within $overOU"
    } else {
      Write-Host "OUen $navnpaaou do exist within $overOU"
    }
  } else {
    Write-Host "OUen $overOU doesen't exist, trie again"
  }
}

This is my script, the purpose of which is to create a OU unless it already exist. I just can't figure out what's wrong with my code.

Upvotes: 4

Views: 25793

Answers (2)

bobmagoo
bobmagoo

Reputation: 368

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"

Upvotes: 3

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

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
}

Upvotes: 6

Related Questions