doenoe
doenoe

Reputation: 322

Check if OU exists not working properly

Wrote this small script to test if an OU exists, if exists write to console and terminate. If not exists create OU and do some other stuff. Though can't seem to understand why i cant get it working.

For some reason the output will always tell me that the OU exists, and I am pretty sure it does not. Am I doing something terribly wrong?

This is the code:

param (
    [parameter(mandatory=$true)] [string] $servername
)

Import-Module ActiveDirectory

Function CheckOU {
    $script:OUpath = "OU=$servername,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com"
    $Status = $false
    $GetOU = Get-ADOrganizationalUnit -Identity $OUpath -ErrorAction SilentlyContinue

    if ($GetOU -eq $null) {
        $status = $false
        Write-Host -ForegroundColor Green "$OUpath does not exist." 
    } else {
        $Status = $true
        Write-Host -ForegroundColor Red "$OUpath exists!"
    }
    return $Status
}

$OUStatus = CheckOU

if ($OUStatus -eq $true) {
    Write-Host "$OUpath exists. Function working."
} else {
    Write-Host "$OUpath does not exsist, do something."
}

Output:

Get-ADOrganizationalUnit : Directory object not found
At C:\Scripts\CreateOUgroups\createadgroups_test02.ps1:10 char:14
+     $GetOU = Get-ADOrganizationalUnit -Identity $OUpath -ErrorAction SilentlyCon ...
+              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (OU=notexistsing...c=Doenoe,DC=com:ADOrganizationalUnit) [Get-ADOrganizationalUnit], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit

OU=notexistsingOU,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com exists!
OU=notexistsingOU,OU=Rechtengroepen,OU=danny,dc=Doenoe,DC=com exists. Function working.

Upvotes: 1

Views: 2657

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

Using the cmdlet with the -Identity parameter causes a terminating error if the object with the given identity doesn't exist. Use -Filter to avoid this issue:

Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OUPath'"

Upvotes: 4

Related Questions