Accounts in an OU of an organization may often need to be moved, each departmental OU has a departmental group, beginning with Dep_, if the account is moved from OU1 to OU2, the account needs to be removed from the departmental group in OU1, and the script to be added to the OU2 Department group is as follows:
$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_开始的名称的组中, if not in the group, the subsequent loop adds the user to the group
{
$outinfo = "Adding" + $user. name+ "to" + $group. Name + ' in ' + $ou. distinguishedname
Out-file-filepath $filepath. Txt-inputobject $outInfo-append
Add-adgroupmember $group-members $user 2>> $filepath. Txt
}
}else {
$outinfo = "The Group Does not exist in" + $ou. distinguishedname >> $filepath. Txt
Out-file-filepath $filepath. 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中的用户, if any, subsequent loops delete the user in the group
{
$outinfo = "removing" + $member _new.name+ "from" + $group. Name + "in" + $ou. distinguishedname
Out-file-filepath $filepath. Txt-inputobject $outInfo-append
remove-adgroupmember-identity $group -members $member _new 2>> $filepath. Txt
}
}
}
}
}
This article from "Bo shen" blog, reproduced please contact the author!
Active Directory PowerShell add \ Remove users from a group