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
}
}
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"
}