Hello!
I am using Try/Catch with New-ADUser. I am intentionally breaking the add by giving a bad syntax for the -Path argument.
I have three objects being input to my script. They all three error. $error.count shows 3 errors when I run this script.
However, my error variable, which is set up like, -ErrorVariable ADFail, only shows the last occurrence instead of all three.
When I run $ADFail, I see a perfectly caught exception, but only for the last failure.
How can I get $ADFail to show all instances??
$newStaff | ForEach-Object { Try { if ($_.ElemOrSecOU -ne "NULL") { $path = "OU=$($_.LocationOU),OU=$($_.ElemOrSecOU),OU=$($_.CertOU),OU=User Accounts,DC=domain,DC=my" } Else { $path = "OU=$($_.abbrOtherOU),OU=$($_.CertOU),OU=User Accounts,DC=domain,DC=my" } New-ADUser -Name ($_.FirstName + ' ' + $_.LastName) ` -Surname $_.LastName ` -DisplayName $_.DisplayName ` -GivenName $_.FirstName ` -EmailAddress $_.EmailAddress ` -SamAccountName $_.UserLogonName ` -UserPrincipalName ($_.UserLogonName + '@my.domain') ` -Title ($_.WorkDuties) ` -HomeDrive "H:" ` -HomeDirectory ($_.HomeServer + '\HOME\' + $_.UserLogonName) ` -Path $path ` -AccountPassword (ConvertTo-SecureString "mypass" -AsPlainText -force) ` -ChangePasswordAtLogon $true ` -Enabled $true ` -ErrorVariable ADFail } Catch [Microsoft.ActiveDirectory.Management.ADException] {$ADFail} $AccountAddFail = $_.UserLogonName + ' ' + $ADFail }
$ADFail looks like this…
PS C:\Windows\system32> $AccountAddFail
USERNAME1 System.Management.Automation.CmdletInvocationException: The object name has bad syntax —> Microsoft.ActiveDirectory.Management.ADException: The object name has bad syntax —> System.ServiceModel.FaultException: Active Directory returned an error processing the operation.
— End of inner exception stack trace —
It should be…
USERNAME1 error
USERNAME2 error
USERNAME3 error
…right??
Any advice appreciated. Thank you!