Reputation: 5
I'm currently attempting to find out which members of a particular group have not logged into AD within the last 30 days. I've managed to return all users of the group but I'm having problems when piping this to a Foreach-object loop.
import-module activedirectory
$DaysInactive = 30
$time = (Get-Date).Adddays(-($DaysInactive))
get-adgroupmember -identity "Remote Users" | foreach-object {
if ($_.LastLogonDate -lt $time) {
write-host $_.SamAccountName
}
}
I think the problem is that I'm using an AD user attribute when calling LastLogonDate and as a result I receive an error saying that it is not recognised.
I'm imagining that within the loop I need a get-aduser
cmdlet but I'm unsure what to send as the value for -filter
.
When PowerShell retrieves all members from the get-adgroupmember
does it place the result set in an array? If so how can I retrieve the value of last logon date?
Upvotes: 0
Views: 1841
Reputation: 1749
Something like this?
Get-ADGroupMember -recursive -identity "Remote Desktop" |
Where { $_.objectClass -eq "user" } |
Get-ADUser -properties SamAccountName, LastLogonDate |
Where { $_.LastLogonDate -lt $time } |
select SamAccountName
Upvotes: 1
Reputation: 37790
Alright, I don't have the time to fully test this so it is off the cuff, but this should get you going in the right direction:
import-module activedirectory
$DaysInactive = 30
$time = (Get-Date).Adddays(-($DaysInactive))
$users = get-adgroupmember -identity "Remote Users"
foreach($user in $users){
$lastLogin = (Get-ADUser $user -Property LastLogonDate).LastLogonDate
if($lastLogin -lt $time){
Write-Host $user.SamAccountName
}
}
Upvotes: 0