Jay Phillips
Jay Phillips

Reputation: 3

Copy workstation AD groups from one computer to another while ignoring existing workstation groups

I am trying to write a script that will copy a workstations group memberships from Active Directory from one computer to another. I am also trying to accomplish that if one or more group memberships already exist, then ignore it and just add the ones that do not exist. I was able to get it to copy over the groups but when it sees that it is already a member of a group, it will error out.

Here is a sample of my code...

################################
Copy-ADWorkstationGroups.ps1 
################################

# Import the Active Directory Module into PowerShell
Import-Module ActiveDirectory

#    Display "This script will copy over the workstation groups from one computer to another."
Write-Output "This script will copy over the workstation groups from one computer to another."

##########################################################################
# Define Variables

# Source is the computer to copy group memberships from.
$Source = Read-Host "Enter the source computer name"

# Destination is the computer to copy group memberships to.
$Destination = Read-Host "Enter the destination computer name"

# OUPath is the South Bend OU in AD Computers & Users
$OUPath = "OU="1st OU",OU="2nd OU",DC="mydomain",DC=org"

# PDC is the Primary Domain Controller
$PDC = "Domain Controller"

# SRC is telling the script exactly where the source computer is.
$SRC = Get-ADComputer -SearchBase $OUPath -Filter "name -like '$Source*'" -Server $PDC -Properties memberOf

# DST is telling the script exactly where the destination computer is.
$DST = Get-ADComputer -SearchBase $OUPath -Filter "name -like '$Destination*'" -Server $PDC

# creds is the location of my admin account credentials & password (secured)
$creds = H:\Scripts\PowerShell\Get-myCredential.ps1 "myusername"   
H:\Scripts\PowerShell\Credentials\"myusername".txt

##########################################################################

 # For each workstation group in the source computer, add the same groups to the destination computer.

foreach ($ComputerGroup in $SRC.memberOf) {
    if($SRC.MemberOf -notcontains $ComputerGroup) {
        Add-ADGroupMember -Identity $ComputerGroup -Member $DST -Credential $creds
    } 

    Write-Output $ComputerGroup
}

Write-Output " " 
Write-Output " " 

Write-Output "Finished!"

Upvotes: 0

Views: 2496

Answers (1)

Frode F.
Frode F.

Reputation: 54881

If($SRC.MemberOf -notcontains $ComputerGroup) {

This excludes every group in your loop. The script will only output group names to the screen. Replace the line with

if($DST.MemberOf -notcontains $ComputerGroup) {

And update the $DST = line to:

$DST = Get-ADComputer -SearchBase $OUPath -Filter "name -like '$Destination*'" -Server $PDC -Properties MemberOf

Upvotes: 1

Related Questions