I have one of my first PowerShell scripts that will query a list of users in Active Directory. While doing so it will keep a tally in a hashtable that will update for every group increasing it count so that a final total can then be displayed.
This is used so that given a group of users that are performing the same job I can create a role based security group in AD and move all the related groups into it. Thereby reducing the amount of work and thought involved when creating new users and making changes to existing departments.
<#
Script : Count Group Memberships
Created By : Matt Something
Created : November 28, 2012
Modified : November 28, 2012
This script will take a list of samaccountnames from active directory and count the membership lists between them. This
is used to track the similarities between accounts.
#>
param (
[parameter(ValueFromRemainingArguments=$true)]
[string[]]$userNamesToCheck = $(throw "Need to supply at least one username")
)
# Functions and Subroutines
Function Get-NamedModule {
Param([string]$name)
if(-not(Get-Module -name $name)) {
if(Get-Module -ListAvailable | Where-Object { $_.name -eq $name }) {
# Check the list of available module for $name. If present import it.
Import-Module -Name $name
$true
}
else { $false } # Module not available
} # End if
else { $true } # Module already loaded
} # End function
# Variable Declaration
$counts = @{}
# Main
# Import the activedirectory module if its not already.
[void](Get-NamedModule -name "activedirectory")
# Cycle through usernamestocheck and get their group memberships
$userNamesToCheck | ForEach-Object{
# Get the group memberships from each user.
$memberships = (Get-AdUser -Filter { SamAccountName -eq $_ } -Properties MemberOf).MemberOf
# Add the groups to a table for counting
$memberships | ForEach-Object{
[void]($_ -match "^CN=(?<membership>.*?),")
# Continue to build the table
$singleGroup = $matches.membership
If($counts.ContainsKey($singleGroup)){
# This group already exists in the table.
$counts.Set_Item($singleGroup, [int]($counts.($singleGroup)) + 1)
} else {
$counts.Add($singleGroup, 1)
}
}
}
Write-Host "$((Measure-Object -InputObject $userNamesToCheck).Count) users checked"
$userNamesToCheck
$counts.GetEnumerator() | Sort-Object -Property Value -Descending