'pull ad groups owned by inactive user in managed by field

Im trying to pull all the ad groups which has inactive user as an owner(managed by) field.I have a script which can pull all the groups and its managed by field but what im looking for is to pull only groups that has inactive user in managed by field.



Solution 1:[1]

You could implement a simple 3-step process with the RSAT ActiveDirectory PowerShell module:

  1. Find all disabled accounts with Get-ADUser
  2. Find all groups with a manager with Get-ADGroup
  3. Compare the second list against the first one

Let's start by pulling the distinguished name of each disabled account:

# prepare a hashtable, we'll store all the distinguished names in here for easy lookup later 
$disabledDNs = @{}
Get-ADUser -Filter "Enabled -eq '$false'" |ForEach-Object { $disabledDNs[$_.DistinguishedName] = $true }

Now that we know the identity of all disabled accounts, let's fetch all the groups that have a ManagedBy value set. The -Filter parameter doesn't support this type of query, so we'll use the -LDAPFilter option instead:

$managedGroups = Get-ADGroup -LDAPFilter '(managedBy=*)' -Properties ManagedBy

Now that we have both pieces of information, we simply need to go through the list of groups and test if the manager is in the disabled users pile - a perfect job for Where-Object:

$orphanedGroups = $managedGroups |Where-Object { $disabledDNs.ContainsKey($_.ManagedBy)) }

$orphanedGroups now contain the groups that have a disabled user account as its manager

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen