Populate AD Group from profile

Today we needed to collect all the users who had logged in the last 90 days on one of our remote desktop servers. This script looks at the user profile directories last write time to determine last login and then put all users who has logged in last 90 days in an array. After that it creates a new AD-group and populates the group with the users from the array.

#NAME: PopulateAdGroupFromProfile.ps1 
#AUTHOR: Viktor Lindström
#COMMENTS: This script fetch users who logged in the last 90 days,
#and the creates a securitygroup and put all the users in that group.
#Get users who have used the server last 90 days
$date= (get-date).AddDays(-90)
$users = Get-ChildItem J:\Users | where LastWriteTime -GT $date
$count = $users.Count
Write-Host "Det är $count stycken användare som använt fjärrskrivbordet senaste 90 dagarna"

#Create new AD group
$group = "BG Fjärrskrivbord"
New-ADGroup -Name "$group" -GroupCategory Security -GroupScope Global -path "OU=Global,DC=contoso,DC=com" -Description "Behörighetsgrupp för användare som ska använa fjärrskrivbordet på srv-xxxxxxxx"

# check if group is created, and if it is populate group with the users who have used the server last 90 days
$adgrupp = $null
$adgrupp = Get-ADGroup $group

if ($adgrupp -eq $null)
{Write-Host "Group does not exist"
foreach ($user in $users)
{Add-ADGroupMember -Identity "$group" -Members $user.name}