Reputation: 167
I am trying get users from Active Directory. The list of the users is presented in file users.txt. I when I do a bulk query I want to export all details in a CSV while I keep the headers (column names). Also I want to handle the errors in file errors.txt.
Here is a fragment from my code:
$Users = Get-Content .\users.txt
try {
$Users | Get-ADUser -Properties * | select * | Export-Csv export.csv
} catch {
$_ | Out-File errors.txt -Append
}
But I got onscreen errors instead in a file. For example:
Get-ADUser : Cannot find an object with identity: 'admin' under: 'DC=test,DC=dev,DC=net'. At line:2 char:14 + $Users | Get-ADUser -Properties * | select * | Export-Csv export.csv + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (admin:ADUser) [Get-ADUser], ADIdentityNotFoundException + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
I don't want to use a loop like foreach
because I can't append to the CSV file. Also I lose column names.
The question is how I can handle errors in a file when I execute $Users | Get-ADUser
for multiple users?
Upvotes: 2
Views: 1980
Reputation: 200483
The errors are non-terminating errors, so they're not caught by try..catch
. Redirect error output from the (potentially) failing command to a file and leave the rest to the pipeline. BTW, select *
is useless, so just remove that part.
$Users |
Get-ADUser -Properties * 2>> 'errors.txt' |
Export-Csv 'export.csv' -NoType
Upvotes: 0
Reputation: 150
This is most likely because your ErrorAction is not properly set. Just add -ErrorAction Stop to your Get-ADUser command and see if that corrects the issue. Otherwise it may not activate your catch.
To elaborate, the error you're seeing on screen is most likely not a terminating error and so it doesn't activate your catch, so specifying the -ErrorAction Stop will cause non-terminating errors to enter the catch and capture the error for you in the text file. However if you don't want your pipeline to terminate during this, read the edit below.
Edit, I realize you may not want your pipeline to terminate when a non-terminating error occurs. If that is the case you'll need change a couple of things.
#Start by clearing out errors before you execute your pipeline code. Do not put a try catch on it.
$Error.Clear()
$Users | Get-ADUser -Properties * -ErrorAction SilentlyContinue | select * | Export-Csv export.csv
$Error | Out-File C:\TEMP\errors.txt -Append
Upvotes: 1