powershell - Remove all groups withen a specific OU
问题描述
I'm attempting to make an AD cleanup script that will go through a terminated OU and verify all users are removed from specific OU's. currently if I run it it will remove all users in the terminated OU from all OU's. I might just be blind but is there an easy way to have it only remove groups from selected OU's?
$OUs = "OU=Terminated,OU=####,OU=####,DC=####,DC=####"
$results = foreach ($OU in $OUs) {
get-aduser -SearchBase $OU -filter * -properties MemberOf | foreach-object {
? $_.MemberOf -like "*OU I want removed*" | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false -whatif
}
}
$results | Export-Csv '.\Users groups have been remoed from.csv' -NoTypeInformation
I thought it would work, however all it gives me is:
Where-Object : A positional parameter cannot be found that accepts argument 'Microsoft.ActiveDirectory.Management.ADPropertyValueCollection'.
At C:\###\###\###\accounts script.ps1:8 char:13
+ ? $_.MemberOf -like "*Distrobution Lists*" | <#%{$keep -n ...
解决方案
鉴于您有一个单独的组 OU,您可以遍历已终止用户拥有的组,并查看是否有任何组属于该特定 OU。如果是这样,则删除所有这些组。
$results = ""
foreach ($ou in $OUs)
{
$users = Get-ADUser -SearchBase $ou -Filter *
foreach ($user in $users)
{
$groups = Get-ADPrincipalGroupMembership -Identity $User | ? {$_.distinguishedName -like "*OU I WANT TO REMOVE FROM*" }
foreach($group in $groups)
{
Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $group -whatif
results += "$user removed from its Groups: $($groups | % { $_.name })\r\n"
}
}
}
results | Out-File -Append C:\temp\new.txt
$groups 将有这种格式的成员。您可以使用 distinctName 作为过滤器类型,并使用“OU=Groups,DC=this,DC=com”之类的东西,而不是可能被认为是宽泛的“OU=Groups”。
distinguishedName : CN=GroupName,OU=****,DC=****,DC=****
GroupCategory : Security
GroupScope : Global
name : <Name Of The Group>
objectClass : group
objectGUID : <Object Guid>
SamAccountName : <Name Of The Group>
SID : <SID>
我喜欢保留变量,这样我就可以使用它们来记录正在执行的更改。
注意:出于测试原因,我曾经-whatif
确保它不会做您打算做的事情。Remove-ADPrincipalGroupMembership
还用一组更新用户。
另一种解决方法
foreach ($ou in $OUs)
{
$users = Get-ADUser -SearchBase $ou -Filter *
$groups = Get-ADGroup -Filter * -SearchBase $DecomOUGROUP
foreach($group in $groups) {
Remove-ADGroupMember -Identity $group -Members $users -ErrorAction SilentlyContinue
}
}
推荐阅读
- c++ - NRVO for C++ std::string
- c# - 所有用户和会话都使用相同的 asp.net sessionID
- sql - 如何构建丢弃重复数据的 SQL 查询?
- python - 如何将字符串年-日-年-毫秒转换为日期时间对象
- javascript - 如何优化列表所有猫鼬查询?
- javascript - 在 Node.js 和浏览器中排序数组结果不同
- django - django 模型保存方法的奇怪行为。“(1048,“列'created_at'不能为空”)“在具有auto_now_add = True的字段上
- symfony - OVH 服务器上的 symfony 4.3,缓存清除返回错误 255(同时 composer update / heroku deploy from github)
- azure - 使用 Get-AzTable Powershell 脚本从 Azure 表访问数据时出错
- c - 编写一个在 C 中创建锯齿状 2D 零数组的函数