• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

PowerShell - Move errors to file

Dear Experts,

I have been running this command to remove users from a certain Active Directory group, basically their names are listed in a .csv file column and from there imported, then for each the command executed and putting the errors to a .txt file:

Import-Csv C:\users\z.cseh\desktop\displaynames.csv | ForEach {remove-adgroupmember -Identi
ty "Users" -Member $_.displayname -Confirm:$false} 2>> c:\users\z.cseh\desktop\DisplayNamesErr.txt


In general that works fine, but relating the errors the issue is that it puts to the .txt file when error happens, but not showing at which .csv line or at which users. Always just repeating this pattern:

errors.png
Could you please advise how to parameterise somehow to show at least at which .csv line the error happened?

Thanks,
0
csehz
Asked:
csehz
1 Solution
 
SubsunCommented:
Try this code.. DisplayNamesErr.csv will have the details of error..
Import-Csv C:\users\z.cseh\desktop\displaynames.csv | ForEach {
$Group = $_.displayname
Try{
remove-adgroupmember -Identity "Users" -Member $Group -Confirm:$false -EA Stop
}Catch{
	New-Object PSobject -Property @{
	GroupName = $Group
	Error = $_.exception.message
	}
}
} | Export-Csv c:\users\z.cseh\desktop\DisplayNamesErr.csv -nti

Open in new window

0
 
csehzAuthor Commented:
That is great like that the error message and also the users appeared in the file, thanks very much
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now