Powershell check if OU exists

I am trying to check if an OU exists before it is created. My problem is that I have 2 parent OU "SITE USER" and "SITE GROUP", and I need to have the same unit in those 2, 1 for storing users, and another for storing groups.

So far I have used this function:

function CheckOUExist { param($OUToSeek) $LDAPPath = "LDAP://dc=Domain,dc=local" $seek = [System.DirectoryServices.DirectorySearcher]$LDAPPath $seek.Filter = "(&(name=$OUToSeek)(objectCategory=organizationalunit))" $Result = $seek.FindOne() return $Result } 

There is my problem, I always get the OU existing in "GROUP BY SITE", even if $ LDAPPath = "OU = USERS ON THE SITE, DC = Domain, DC = local". Am I missing something there? Is there a way for [System.DirectoryServices.DirectorySearcher] to work only in the OU that I received in $ LDAPPath?

If you need more accurate parts, I gladly provided them.

Thanks in advance.

+6
source share
5 answers

Try the Exists method, you will return true / false accordingly:

 [adsi]::Exists("LDAP://OU=test,DC=domain,DC=com") 
+10
source

The following, as suggested by Shay, works great if you work with clean data.

 [string] $Path = 'OU=test,DC=domain,DC=com' [adsi]::Exists("LDAP://$Path") 

Thanks for this great starting point! However, if you check for potentially impure data, you will receive an error message. Some examples of possible errors:

  • If something is not formatted correctly
    • (ERR: invalid dn syntax specified)
  • If the domain does not exist
    • (ERR: server is down)
  • If the domain does not contact you
    • (ERR: referral was returned from the server)

All of these errors must be caught using [System.Management.Automation.RuntimeException] or you can just leave the catch statement empty to catch everything.

Quick example:

 [string] $Path = 'OU=test,DC=domain,DC=com' try { $ou_exists = [adsi]::Exists("LDAP://$Path") } catch { # If invalid format, error is thrown. Throw("Supplied Path is invalid.`n$_") } if (-not $ou_exists) { Throw('Supplied Path does not exist.') } else { Write-Debug "Path Exists: $Path" } 

More details: http://go.vertigion.com/PowerShell-CheckingOUExists

+12
source

The problem is creating the DirectorySearcher object. To set the search root correctly, DirectorySearcher must be constructed using a DirectoryEntry object (ADSI type accelerator), while you are using a string. When a string is used, the string is used as an LDAP filter, and the search root is null, forcing the crawler to use the root of the current domain. That's why it looks like you are not looking for the OU that you want.

I think you will get the results you are looking for if you do something like the following:

 $searchroot = [adsi]"LDAP://OU=USERS BY SITE,DC=Domain,DC=local" $seek = New-Object System.DirectoryServices.DirectorySearcher($searchroot) $seek.Filter = "(&(name=$OUToSeek)(objectCategory=organizationalunit))" ... etc ... 

Note that the DirectoryEntry constructor is created first, which is then used to create the DirectorySearcher.

+2
source

What about:

 #Requires -Version 3.0 # Ensure the 'AD:' PSDrive is loaded. if (-not (Get-PSDrive -Name 'AD' -ErrorAction Ignore)) { Import-Module ActiveDirectory -ErrorAction Stop if (-not (Get-PSDrive -Name 'AD' -ErrorAction Silent)) { Throw [System.Management.Automation.DriveNotFoundException] "$($Error[0]) You're likely using an older version of Windows ($([System.Environment]::OSVersion.Version)) where the 'AD:' PSDrive isn't supported." } } 

Now that PSDrive AD: loaded, we have several options:

 $ou = "OU=Test,DC=Contoso,DC=com" $adpath = "AD:\$ou" # Check if this OU Exist Test-Path $adpath # Throw Error if OU doesn't exist Join-Path 'AD:' $ou -Resolve 

Additional information on this topic: Playing with AD: Drive for Fun and Profit

+1
source
 Import-Module ActiveDirectory Function CheckIfGroupExists{ Param($Group) try{ Get-ADGroup $Group } catch{ New-ADGroup $Group -GroupScope Universal } } 

Will also work

-1
source

Source: https://habr.com/ru/post/893575/


All Articles