$sourceOU = "OU=Workstations,OU=11,OU=Filials,DC=domain,DC=local"
$destinationOUs = Get-Content C:\ou.txt
foreach ($destinationOU in $destinationOUs)
{
$adPath= "LDAP://" + $destinationOUs
import-module activedirectory
#Create OUs
$objDomain=New-Object System.DirectoryServices.DirectoryEntry($adPath)
$ObjSearch=New-Object System.DirectoryServices.DirectorySearcher($ObjDomain)
[array] $OUs = @()
$OUs = dsquery * $sourceOU -Filter "(objectCategory=organizationalUnit)" -limit 0
$OUsorted = $OUs | sort-object { $_.Length}
for ($k=0; $k -le $OUsorted.Count -1; $k++)
{
$OUtoCreate = ($OUsorted[$k] -replace $sourceOU,$destinationOUs).ToString()
$OUSearch = ($OUtoCreate -replace '"',"").ToString()
$ObjSearch.Filter = "(&(objectCategory=organizationalUnit)(distinguishedName="+ $OUSearch + "))"
$allSearchResult = $ObjSearch.FindAll()
if ($allSearchResult.Count -eq 1)
{
"No changes were done on = " + $OUtoCreate
}
else
{
dsadd ou $OUtoCreate
"OU Creation = " + $OUtoCreate
}
}
}
Exception calling "FindAll" with "0" argument(s): "Unknown error (0x80005000)"
At line:30 char:5
+ $allSearchResult = $ObjSearch.FindAll()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
dsadd : dsadd failed:OU=Workstations,OU=22,OU=Filials,DC=domain,DC=local OU=Workstations,OU=Ag. Krilatskoe,OU=Filials,DC=domain,DC=local:Directory object
not found.
At line:37 char:9
+ dsadd ou $OUtoCreate
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (dsadd failed:OU...ject not found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
type dsadd /? for help.
OU Creation = "OU=Workstations,OU=22,OU=Filials,DC=domain,DC=local OU=Workstations,OU=Ag. Krilatskoe,OU=Filials,DC=domain,DC=local"