Skip to content

Instantly share code, notes, and snippets.

@in03
Created February 21, 2025 00:24
Show Gist options
  • Save in03/f191f7a14bfcfe7d0b03504f7d8ae754 to your computer and use it in GitHub Desktop.
Save in03/f191f7a14bfcfe7d0b03504f7d8ae754 to your computer and use it in GitHub Desktop.
Recursively check active computers in a computer group based on `LastLogonDate`
# Define the group name
$ADGroupName = "My-AD-Computer-Group"
# Get the current date and calculate the threshold for last logon (365 days ago)
$DaysThreshold = 365
$LastLogonCutoff = (Get-Date).AddDays(-$DaysThreshold)
# Function to recursively get members of a group, including nested groups
function Get-ADGroupMembersRecursive {
param (
[string]$GroupName
)
$Members = Get-ADGroupMember -Identity $GroupName -Recursive | Where-Object { $_.objectClass -eq "computer" }
return $Members
}
# Get all computers in the AD group (including nested)
$Computers = Get-ADGroupMembersRecursive -GroupName $ADGroupName
# Get last logon date for each computer and filter by last 365 days
$ActiveComputers = $Computers | ForEach-Object {
$Computer = Get-ADComputer -Identity $_.DistinguishedName -Properties LastLogonDate
if ($Computer.LastLogonDate -gt $LastLogonCutoff) {
$Computer
}
}
# Output the final count
$ActiveComputers.Count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment