This script reads (non-unique) departments from a CSV file with user records and transforms it into a unique list. It then create OU’s in Active Directory based on the departments in the file.

Replace <RootOU>, <DomainName> and "MyCity" for appropriate values.

$FileToRead = Read-Host "Please enter the filename"

$Departments = Import-Csv $FileToRead -Delimiter ";" | sort Department -Unique

foreach ($Record in $Departments){
    if ($Record.ParentDepartment -eq "") {
        $Dept = $Record.Department
        $Path = "OU=<RootOU>,DC=<DomainName>,DC=local"
        Write-Host "[INFO] Creating $Dept in $Path"
        New-ADOrganizationalUnit -Name $Dept -Path $Path -Description "OU for $Dept" -ProtectedFromAccidentalDeletion 0 -City "MyCity" -PassThru
    }
}