powershellou

Verify that an OU exists


I want to find out if an organisational unit exists or not so I wrote this following code but it shows up an error : Impossible to find object with the identity OU_Bloquage.Despite it does really exist(I've created it) Below is the code I've wrote

Import-Module ActiveDirectory
Import-Module 'Microsoft-PowerShell.Security'
$OUName = 'OU_Bloquage'
if([bool] (Get-ADOrganizationalUnit $OUName))
{ Write-Host 'true' }
else { Write-Host 'false' }

Solution

  • @Bearded Brawler -- You're close, but missing the context of the rest of the question.

    Instead:

    $OUName = 'OU_Bloquage'                  # the OU your looking for.
    
    $OUName = "Name -like '$($OUName)'"
    if([bool](Get-ADOrganizationalUnit -Filter $OUName)) {
     Write-Host 'true'
    } else {
      Write-Host 'false' }
    

    Note: This assumes the OU is actually 'OU_Bloquage' and not actually 'Bloquage'. If it is just Bloquage then edit the first line to read as such.