Tag Archives: caching

Efficiently Retrieve Active Directory Group Members with PowerShell and Caching

Retrieving Active Directory group members can be a time-consuming process, especially for large groups. This can cause slowdowns in your PowerShell scripts and lead to poor performance. Fortunately, there’s a solution: PowerShell caching. In this post, I’ll show you how to optimize the process of retrieving AD group members with caching, resulting in faster script execution and improved performance.

The “Get-CachedADGroupMembers” Function

The “Get-CachedADGroupMembers” function takes the name of the AD group to retrieve members from.

$cache = @{}
function Get-CachedADGroupMembers {
    if ($cache -eq $null) {
        $cache = @{}
    if ($cache.ContainsKey($group_name)) {
        return $cache[$group_name]
    } else {
        $data = ((Get-ADGroupMember -Identity $group_name -Recursive | %{
            if ($_.objectClass -eq "computer") {
            } else {
                $_.SamAccountName | Get-ADUser -Properties samAccountName, employeeType 
        } | select samAccountName,employeeType,enabled) | Where {$_.samAccountName -notin $excluded_users})
        $cache[$group_name] = $data
        return $data

The function first checks if the $cache variable has been initialized. If it hasn’t, it initializes it as an empty hashtable. It then checks if the group_name exists in the hashtable. If it does, the function returns the cached data. If it doesn’t, the function retrieves the group members using the “Get-ADGroupMember” cmdlet and stores the results in the $data variable. The function then adds the $data variable to the $cache hashtable and returns the $data variable.

The function also uses a pipeline to filter out any members that are computers and to retrieve additional user properties using the “Get-ADUser” cmdlet. Finally, it uses the “Where” cmdlet to exclude any users in a specified list of excluded users.


By using PowerShell caching, you can significantly speed up the process of retrieving Active Directory group members, resulting in faster script execution and improved performance. The “Get-CachedADGroupMembers” function is a simple and effective way to implement caching in your PowerShell scripts. Give it a try and see how much time you can save!