Saturday 10 December 2022

How to Count the Number of Users in a Group in Active Directory using PowerShell

To create a script that counts the number of users in a group in AD using PowerShell and the Get-ADGroupMember cmdlet, while specifying the domain name as part of the Get-ADGroupMember command, you can use the following code:

Import-Module ActiveDirectory

# Prompt the user for the name of the domain
$domain = Read-Host "Enter the name of the domain"

# Prompt the user for the name of the group to count
$group = Read-Host "Enter the name of the group"

# Get the members of the group and count them
$count = (Get-ADGroupMember -Server $domain -Identity $group).Count

# Output the result
Write-Output "There are $count members in the $group group."

To use this script, simply copy and paste it into a text editor and save it with a .ps1 file extension. Then, open a PowerShell prompt and navigate to the directory where you saved the script. Run the script by typing the following command and pressing Enter:

.\script_name.ps1

Replace "script_name" with the actual name of the script file. This will prompt you for the name of the domain and the name of the group, and then output the number of users in the group.

No comments:

Post a Comment