将工作站AD组从一台计算机复制到另一台,同时忽略现有工作站组
问题描述:
我正在尝试编写一个脚本,用于将工作站组成员身份从Active Directory从一台计算机复制到另一台计算机。如果一个或多个组成员资格已经存在,我也试图做到这一点,然后忽略它并只添加那些不存在的组成员。我能够将它复制到组中,但当它看到它已经是组的成员时,它将会出错。将工作站AD组从一台计算机复制到另一台,同时忽略现有工作站组
这里是我的代码示例...
################################
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!"
答
If($SRC.MemberOf -notcontains $ComputerGroup) {
这不包括各组的循环。该脚本只会将组名称输出到屏幕上。替换
if($DST.MemberOf -notcontains $ComputerGroup) {
行和更新$DST =
行:
$DST = Get-ADComputer -SearchBase $OUPath -Filter "name -like '$Destination*'" -Server $PDC -Properties MemberOf
何必摆在首位检查?如果计算机已经是该组的成员,则“Add-ADGroupMember”只会默默继续。 –
我不会默默地称它为输出错误(除非你改变错误),但我同意你的看法。我个人从不首先检查,但我想告诉他如何修复他当前的代码。 :-) –
我刚刚检查了Server 2012 R2并没有收到错误消息。 –