How to copy a SharePoint group from one site collection to another

I started working on this task a few days ago but I was not very lucky, I was not careful enough and I’ve spent a lot more time than usual. I am trying to copy a few groups from one site collection to another, instead of recreating them manually. You must add to this script the source and target site collection and then filter for the groups you are interested to copy. Make sure the owner(group or user) exists in the destination site collection, don’t load this variable from the source site collection as this will give you big problems if you choose a group. The groups are unique for each site collection. I loaded the owner group from the ┬ásource site collection and the groups I created were corrupt. I had to make changes in the content DB directly, a procedure which is not recommended by anyone. The following script will create groups with the same name, same members, your defined owner and by default only the owner will be able to change the content of the group. It will also copy the group description.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
#Input variables
$SourceWebURL = "http://source"
$TargetWebURL = "http://destination"
#In my scenario I will add a SharePoint group as the groups owner but you choose to use a user instead, make sure the user or group is available
#in the destination site collection
$ownername = "your owner group name"
#below define your string on which you filter for the groups to copy. You can choose to copy all groups or create your own filtering. 
#I filtered for groups which match a certain string. Change this based on your needs.
$yourstring = "*something*"
#Get the Webs
$SourceWeb = Get-SPsite $SourceWebURL
$TargetWeb= Get-SPWeb $TargetWebURL
$owner = $targetWeb.groups[$ownername]
#Get the Source groups
$SourceGroup = $SourceWeb.rootweb.sitegroups | where {$ -like ($yourstring) }
foreach ($group in $SourceGroup)
 $TargetWeb.SiteGroups.Add($group.Name, $owner, $null, $group.description)
 $destinationGroup = $TargetWeb.SiteGroups["$Group"]
 $destinationGroup.owner = $owner
foreach ($user in $Group.users){$TargetWeb.SiteGroups["$Group"].AddUser($user)}