Copying AD Groups - Capturing Non-Terminating Errors

Copper Contributor

Hello,

I'm very new to Powershell and have been tasked with creating a script that our Service Desk team can use to copy AD users for new account creation. I've been able to get almost everything to work, however, when it comes time to copying the groups from one account to another, I run into a bit of a snag.

 

I was able to get the copy to work, however, there are certain groups that cannot be copied due to insufficient rights on behalf of the service desk employees. This is by design. My script outputs non-terminating errors for each group they do not have rights to. What I am hoping to achieve is to take those errors and list them into a log file that includes the group that could not be copied. 

 

Is there anyone out there with experience listing non-terminating errors that could assist? I've been unable to find anyone who's done this sort of thing. I was able to get a list of errors to be shown within the console, but it simply states "insufficient rights..." for each error message. The code below is what I'm doing to copy from one user to the other. The successfully copied groups will be listed, with their complete Sam Account Name, but the error's Sam Account Name is simply the error message itself.

Any guidance would be appreciated.

 

#Copy Group memberships from copied user to new user.
Get-Aduser -Identity $Copy -Properties Memberof | Select-object -ExpandProperty memberof | Add-ADGroupMember -Members $UserName -passthru | Select-Object -Property SamAccountName

 

write-host $error | Format-List -Force SAMaccountName

2 Replies

Maybe you could do something like this:

$memberof = Get-Aduser -Identity $Copy -Properties Memberof | Select-object -ExpandProperty memberof
foreach($group in $memberof){
$group | Add-ADGroupMember -Members $UserName -passthru -ErrorVairable GroupError
If($GroupError)
{"Failed to add $username to $group"}
}
 
 

This worked and mostly achieved what I was hoping for. My next step would be to take these error messages and return the SamAccountName for these errors rather than the full error. I added Select-Object -Property SAMAccountName at the end of the $group line so the successful group additions would show just the name because without that, it was showing the group and all of it's properties. Unfortunately, I need to make this as user friendly as possible due to the staff that will be using this script. I'm struggling to figure out how I can turn these group errors that are returning with a name, into something a little more user friendly from a text standpoint.

 

$memberof = Get-Aduser -Identity $Copy -Properties Memberof | Select-object -ExpandProperty memberof
foreach($group in $memberof){
$group | Add-ADGroupMember -Members $UserName -passthru -ErrorVariable GroupError | Select-Object -Property SAMAccountName
If($GroupError)
{"Failed to add $username to $group"}
}