powershellactive-directory

Powershell Get-ADGroupMember and Get-ADUser


please tell me how best to filter out AD users who are in the group and who have been active recently?

Get-ADGroupMember $group -Recursive | ? {$_.objectClass -eq "user"} | Get-ADUser -filter {(LastLogonTimeStamp -gt $LastLogonDate)}

in this case I get an error

Get-ADUser: The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

tried to filter

Get-ADGroupMember $group -Recursive | ? {$_.objectClass -eq "user"} | Get-ADUser -Properties LastLogonTimeStamp | ? {$_.LastLogonTimeStamp -gt $LastLogonDate}

got an error

InvalidOperation: Could not compare "133679232082477485" to "07/20/2024 13:23:10". Error: "Cannot convert value "20.07.2024 13:23:10" to type "System.Int64". Error: "Invalid cast from 'DateTime' to 'Int64'.""

Solution

  • It's easier and more efficient to use Get-ADUser with a filter for memberOf. You could also include those users that are Active and those that have lastLogonTimeStamp greater than a date.

    Example:

    # using -30 here (30 days ago, change that accordingly)
    $date = [datetime]::UtcNow.AddDays(-30).ToFileTimeUtc()
    $dn = (Get-ADGroup $group).DistinguishedName
    
    # members of the group (recursively) and
    # lastLogonTimeStamp is greater than or equal to 30 days ago
    $filter = "(&(memberOf:1.2.840.113556.1.4.1941:=$dn)(lastLogonTimeStamp>=$date))"
    Get-ADUser -LDAPFilter $filter
    
    # if you also want to list those users that are also in Active state you can use
    $filter = "(&(memberOf:1.2.840.113556.1.4.1941:=$dn)(lastLogonTimeStamp>=$date)(!userAccountControl:1.2.840.113556.1.4.803:=2))"
    Get-ADUser -LDAPFilter $filter