Count users from AD groups

countThis week I got involved in a project regarding licensing on our remote desktop servers. In phase one I had to do a current situation analysis on how many users that can access our different servers. Since we have 5 different departments the project manager also wanted to have information of how many users the different departments had on each server and a separate excel document for each department with all their users listed. The project manager also hinted that in phase 2 after we made actions and before each license audit we might have to create new reports. Since I am lazy and don´t like to manually create reports I made a function in Powershell  where anyone with the active directory-module can create reports.

function get-UsersFromGroup 
[string] $server)

# Variables for date and exportfile-summary
$date = get-date -Format d
$outfile = "C:\temp\Sammanfattning $server $date.txt"
$tempdir = "C:\temp"

# Get users from AD group depending on server.
switch ($server) {
srv-rcard01 {$users = Get-ADGroupMember r-card_srv-rco01}
srv-rds02 {$users = Get-ADGroupMember "BG Fjärrskrivbord" }
#Since 2 groups with some users in both broups I do a sort-object and unique
srv-procapts01 {$group1 = Get-ADGroupMember Procapita-Funktion-Remoteapp
$group2 = Get-ADGroupMember Procapita-Aldreoms-Remoteapp
$userspro = $group1 + $group2 
$users = $userspro | Sort-Object | Get-Unique}

#Get users from group
#$users = Get-ADGroupMember "$group"
$users2 = $users | Get-ADUser -properties * -ErrorAction SilentlyContinue

#build empty arrays
$KSF = @()
$SAF = @()
$BUF = @()
$KUF = @()
$MSB = @()
$Övriga = @()

#Sort by apartment.
foreach ($user in $users2)
{if($user.DistinguishedName -like "*OU=KSF*")
{$KSF +=$user}
 elseif ($user.DistinguishedName -like "*OU=SAF*")
{$SAF +=$user}
($user.DistinguishedName -like "*OU=BUF*")
{$BUF +=$user}
($user.DistinguishedName -like "*OU=KUF*")
{$KUF +=$user}
($user.DistinguishedName -like "*OU=MSB*")
{$MSB +=$user}
{$Övriga +=$user}

# Write result.
Write-host Sammanlagt är det $users2.count användare
write-host KSF har $ksf.count användare
write-host SAF har $saf.count användare
write-host BUF har $Buf.count användare
write-host KUF har $kuf.count användare
write-host MSB har $msb.count användare
write-host Övriga användare är $övriga.count stycken

#Delete summary-file if it exists.
if (test-path $outfile)
{Remove-Item -Path $outfile

#Check if dircetory c:\temp exist and if not create it.
if ( -Not (Test-Path $tempdir))
 { New-Item -Path $tempdir -ItemType Directory

# Output count-result to file.
Write-Output "Sammanlagt är det $($users2.count) användare" | Out-File $outfile -Append
Write-Output "KSF har $($ksf.count) användare" | Out-File $outfile -Append
Write-Output "SAF har $($saf.count) användare" | Out-File $outfile -Append
Write-Output "BUF har $($Buf.count) användare" | Out-File $outfile -Append
Write-Output "KUF har $($kuf.count) användare" | Out-File $outfile -Append
Write-Output "MSB har $($msb.count) användare" | Out-File $outfile -Append
Write-Output "Övriga användare är $($övriga.count) stycken" | Out-File $outfile -Append

#Export to CSV to c:\temp\
Write-Host Exporterar alla användare till CSV som läggs i c:\temp\[förvaltning.csv]
$msb | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\msb-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"
$ksf | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\ksf-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"
$buf | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\buf-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"
$kuf | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\kuf-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"
$saf | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\saf-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"
$Övriga | select SamAccountName, GivenName, SurNAme, Description | Export-Csv c:\temp\övriga-$server.csv -NoTypeInformation -Encoding UTF8 -Delimiter ";"

#Capture if there is a group in the result.
foreach ($grupp in $users)
if ($grupp.objectclass -like "group") {Write-Host det finns en grupp som heter $ -BackgroundColor Red }

List and count users that never logged on to domain


I got an urgent case from the boss, we had to compare a list of users from our meta-catalog with users in our AD and list and count which users who never logged on to domain. I imported the csv in an variable and then used an foreach-loop to check if the users had logged in or not. We also wanted to list and count all users that where included in the csv-file but not in the active driectory, I used the ErrorVariable to do that and the appended each entry to a text-file with the out-file append switch. As you can see I used two different techniques to export multiple data from the foreach-loop. The first one when I exported the users that hadn´t logged on, where I first created an variable with an empty array  “$users = @()” , then instead of running the command to get the users I used the + to fill the array with result “$users +=”, on the second I used the out-file as I explained above.  When the lists where done I used the count and length property.


#AUTHOR: Viktor Lindström
#COMMENTS: List and count users accounts that never loged on.
#It also lists and counts users that exist in our meta-catalog but
#not in our Active directory

#Import from CSV that contains usesrs samaccountname under header accountname.
$import = Import-Csv "C:\temp\acc.txt"

#Creates an empty array
$users = @()

#foreach loop to check all users.
foreach ($anv in $import)
#Checks if user dont have the lastLogonTimestamp-attribute set, and if it isn´t set it appends users samaccountname in the array. If the user dosn´t exist in the AD it puts one error code-line in an variable.
$users += get-aduser $anv.accountName -ErrorAction SilentlyContinue -ErrorVariable err | Get-ADObject -Properties samaccountname,"lastLogonTimestamp" | where "lastLogonTimestamp" -eq $null | select samaccountname 
$err | Out-File -FilePath "C:\temp\users_not_in_AD.txt" -Append
#Export users to CSV and counts the users.
$users | export-csv -Path c:\temp\users_never_logged_in.txt -NoTypeInformation
Write-Host Number of users who have never logged in: $users.count
$dontexist = Get-Content C:\temp\users_not_in_AD.txt
Write-Host Number of users that are not in active directory $dontexist.Length

Count AD group members

Every year we have to count and report licenses on different systems. Since we use centralized Active Directory security groups to decide which users who gain access to RDS servers etc etc… it`s a pretty easy task to count the users in those groups to find out how many CALs we need. When the boss interrupts you more then once it´s time to use powershell to solve it. This script include one level nested groups.

#NAME: CountAdGroupMembers.ps1
#AUTHOR: Viktor Lindström
#COMMENTS: This script counts and summary members i multiple AD groups.
#It also includes one level nested groups
function count-members

$sum = 0

foreach ($grupp1 in $grupper)
{$grupper3 = Get-ADGroupMember $grupp1 | Where objectclass -eq "group"
$grupper += $grupper3

foreach ($grupp in $grupper)
{$count = Get-ADGroupMember $grupp | Where objectclass -eq "User"
$sum += $count.count