Check if OUs already exists

Viewed 40

This script creates OUs based on a CSV, and places them in the MyLab OU, and also creates 2 subOUs. It also checks if OUs within the CSV already exists, and then outputs it. I have been trying to figure out how do this for the SubOUs as well, so if one of them exist the other is still created. Anyone can point me in the right direction?

#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","

#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"

#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
$Name = $OU.Name 

#Check if an OU within the CSV file already exists
$Check = Get-ADOrganizationalUnit -filter * | Where-Object {$_.name -eq $OU.name} | select name

#If it does the text within the write-host is output
if ( $OU.name -eq $Check.name) {
    write-host $OU.name "OU already exists"}

#if not the OU is created, with a 2 sub ous created within it 
else{New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false

    $SubOUs = "Department1", "Department2"
    $subPath = "OU="+$OU.name+","+$ParentPath
    
    foreach ($SubOU in $SubOUs){
    New-ADOrganizationalUnit -Name $SubOU -Path $subPath -ProtectedFromAccidentalDeletion $false
    }
}

}

1 Answers

To always create the child OUs, you can do another if check, outside of the if that creates the parent OUs. Here's my go at keeping most things the same, but improving the checking for OUs:

#Imports CSV file
$MyOUs = Import-csv C:\OUs.csv -Delimiter ","
#Query existing OUs only once at the start
$existingOUs = Get-ADOrganizationalUnit -filter * 

#Sets parent path to main OU
$ParentPath = "OU=MyLab,DC=MyLab,DC=local"

#Perform actions for each OU in the CSV file
foreach ($OU in $MyOUs){
  # Build distinguished name
  $DN = "OU="+$OU.name+","+$ParentPath

  #check for OU in existing list
  if ($existingOUs.DistinguishedName -contains $DN) { write-host $OU.name "OU $DN already exists" }
  else { 
    New-ADOrganizationalUnit -Name $Name -Path $ParentPath -ProtectedFromAccidentalDeletion $false 
  }

  # then create 2 sub OUs within each $OU
  $SubOUs = "Department1", "Department2"
  foreach ($SubOU in $SubOUs){
    $SubDN = "OU="+$SubOU.name+","+$DN
    
    # check if sub OU exists
    if ($existingOUs.DistinguishedName -contains $SubDN) { write-host $OU.name "OU $DN already exists" }
    else { 
      New-ADOrganizationalUnit -Name $SubOU -Path $DN -ProtectedFromAccidentalDeletion $false 
    }
  }
}
Related