Function that checks if an OU exists in Active Directory always returns false even if there is an existing OU

509 views Asked by At

I am trying to create a powershell function to check if an active directory OU exists and have it return a true or false value to be used in conjunction with another function to create a user. The problem I am having is it always returns a false value, even if the OU exist.

function checkIfOuExists{

param(

    [parameter(Mandatory)]

    [string]$nameOfOU

)

$existingOU = Get-ADOrganizationalUnit -Filter 'Name -like "$nameOfOU"'

if($existingOU -eq $null){
    return $false
}
else{
    return $true
}

}
1

There are 1 answers

0
Scepticalist On BEST ANSWER

There's no need to write a function for this - the behaviour is inherent in Powershell:

$NameofOU = 'Users'
$existingOU = Get-ADOrganizationalUnit -Filter "Name -like '$nameOfOU'"


If ($existingOU) {
    Write-Host "Execute this code if OU exists"
}
Else {
    Write-Host "OU does not exist"
}