MKH_Cerbebrus
MKH_Cerbebrus

Reputation: 51

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

Upvotes: 0

Views: 2422

Answers (3)

user2883951
user2883951

Reputation:

@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.

Upvotes: 1

Sergio Tanaka
Sergio Tanaka

Reputation: 1435

This code should work Filter using Where-Object

Import-Module ActiveDirectory
$OUName = "OU_NAME"
if([bool] (Get-ADOrganizationalUnit -Filter * | ? {$_.Name -eq $OUName} ))
{ Write-Host 'true' }
else { Write-Host 'false' } 

Result:

PS C:\Windows\system32> Import-Module ActiveDirectory
$OUName = "CLOUD"
if([bool] (Get-ADOrganizationalUnit -Filter * | ? {$_.Name -eq $OUName} ))
{ Write-Host 'true' }
else { Write-Host 'false' } 
true

PS C:\Windows\system32> Import-Module ActiveDirectory
$OUName = "dsdsadasda"
if([bool] (Get-ADOrganizationalUnit -Filter * | ? {$_.Name -eq $OUName} ))
{ Write-Host 'true' }
else { Write-Host 'false' } 
false

Upvotes: 0

Bearded Brawler
Bearded Brawler

Reputation: 11

I'd use a filter instead to find an OU that you're not sure of the full path to

Get-ADOrganizationalUnit -Filter 'Name -like "*Bloquage*"' | Format-Table Name, DistinguishedName -A

Upvotes: 0

Related Questions