Answer the question
In order to leave comments, you need to log in
Powershell: foreach not working. Why?
$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"
Answer the question
In order to leave comments, you need to log in
In the $adPath= "LDAP://" + $destinationOUs line, you specified $destinationOUs this variable contains the entire OU array, you should have specified $destinationOU
Similar problems can be easily detected by replacing executable commands with simpler ones, for example Write-Host variable name, immediately everything falls into place and it is clear what is coming from
1. Open the script in Powershell ISE, there is functionality for debugging scripts.
2. Powershell has a native cmdlet for creating an OU - New-ADOrganizationalUnit, why mess with dsadd.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question