Script to add users to an AD group - export file with confirmation of what accounts where added.

Hi EE

I want to use the script below to set a task to add users to a group every night . The Users.txt file will be updated
by the application owner .

can someone help me modify it so the script outputs a file of the SamAccountNames that where added ?
something like  export-csv C:\PS\AddedtoXXXgroup_$((Get-Date -Format MM-dd-yyyy)).csv -NoTypeInformation


Foreach ($User in GC \\Server\Share\Users.txt){
GC C:\PS\groups.txt | % {
Add-ADGroupmember -identity $_ -member $User
      }
}
LVL 2
MilesLoganAsked:
Who is Participating?
 
SubsunCommented:
Try following code which will create a report with status.. check and let me know if it works for you..
$(Foreach ($User in GC \\Server\Share\Users.txt){
GC C:\PS\groups.txt | % {
   $Group = $_
   #using try catch to capture the errors
   Try{
        Add-ADGroupmember -identity $Group -member $User -ea stop
	#create custom PS object to output the command status..
        New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Success"
	}
    }Catch{
	New-Object PSObject -Property @{
	GroupName = $Group
	User = $User
	Status = "Failed"
	}	
     }
   }
}) | export-csv "C:\PS\AddedtoXXXgroup_$((Get-Date -Format MM-dd-yyyy)).csv" -NoTypeInformation

Open in new window

0
 
MilesLoganAuthor Commented:
Subsun .. many thanks as always ! wow
0
 
SubsunCommented:
You are welcome!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.