首页 > 代码库 > 活动目录 powershell 从组中 添加\删除 用户
活动目录 powershell 从组中 添加\删除 用户
某组织的ou中的账户可能经常需要移动,每个部门ou都有部门组,以dep_开头,如果账号从ou1移动到ou2,则账号需要从ou1中的部门组中删除,同时,要添加到ou2的部门组中,脚本如下:
$ConfirmPreference="none" #关闭confirm确认提示
$ou_all=Get-ADOrganizationalUnit -Filter * -SearchBase "OU=sales_ou,DC=test,DC=com"
#查询特定ou
$filePath="c:\"
$datetime=get-date
$date=$datetime.ToString(‘yyyy-MM-dd‘)
foreach ($ou in $ou_all)
{
$group=Get-ADGroup -Filter {name -like "dep_*"} -SearchBase $ou -SearchScope OneLevel
#只查询名称为dep_开头的组
$user_all=Get-ADUser -Filter * -SearchBase $ou -SearchScope OneLevel
#查询当前ou下的所有用户
if ($user_all)
{
foreach ($user in $user_all)
{
if($group)
{
$members=Get-ADGroupMember -Identity $group
if ($members.name -notcontains $user.Name)
#判断用户是否在当前ou的dep_开始的名称的组中,如果不在组中,后面的循环则添加用户到组
{
$outinfo= "Adding " + $user.name+ " to " +$group.name + " in " +$ou.DistinguishedName
Out-File -filePath $filepath$date.TXT -inputobject $outInfo -Append
Add-ADGroupMember $group -Members $user 2>> $filepath$date.TXT
}
}else {
$outinfo= "The Group Does not exist in " + $ou.DistinguishedName >> $filepath$date.TXT
Out-File -filePath $filepath$date.TXT -inputobject $outInfo -Append
}
}
if ($group)
{
$members_new=Get-ADGroupMember -Identity $group
foreach ($member_new in $members_new)
{
if ($user_all.name -notcontains $member_new.name)
#判断组中是否有不在当前ou中的用户,如果有,后面的循环则删除组中的改该用户
{
$outinfo= "Removing "+ $member_new.name+ " from " + $group.Name + " in " + $ou.DistinguishedName
Out-File -filePath $filepath$date.TXT -inputobject $outInfo -Append
Remove-ADGroupMember -Identity $group -Members $member_new 2>> $filepath$date.TXT
}
}
}
}
}
本文出自 “博深” 博客,转载请与作者联系!
活动目录 powershell 从组中 添加\删除 用户