将工作站AD组从一台计算机复制到另一台计算机,同时忽略现有工作站组

时间:2016-03-04 21:41:34

标签: powershell active-directory

我正在尝试编写一个脚本,将Active Directory中的工作站组成员身份从一台计算机复制到另一台计算机。我也试图实现这一点,如果一个或多个组成员资格已经存在,那么忽略它,只添加那些不存在的成员资格。我能够让它复制组,但当它发现它已经是一个组的成员时,它将会出错。

以下是我的代码示例...

################################
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!"

1 个答案:

答案 0 :(得分:1)

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

这会排除循环中的每个组。该脚本仅将组名输出到屏幕。用

替换该行
if($DST.MemberOf -notcontains $ComputerGroup) {

并将$DST =行更新为:

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