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