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?