I am trying to remove inactive users from a Group. I am using lastlogontimestamp to identify inactivity.
I was able to make the same work using the below script.
$DateCutOff=(Get-Date).AddDays(-30)
Get-ADGroupMember Office365 | Get-ADUser -Properties lastLogonTimestamp | select @{N='LastLogon'; E={[DateTime]::FromFileTime($.LastLogontimestamp)}},samaccountname | Where-Object {$.lastLogon -lt $DateCutOff } | foreach { Remove-ADGroupMember Office365 -Members $_.samaccountname -Confirm:$false}
However now my requirement is that only inactive members from a specifc OU should be removed. Rest of the inactive user should remain in the group. I have tried using the search base command. When using the searchbase with Filter after the piping it lists out all users instead of all members of the group.
Get-ADGroupMember Office365 | Get-ADUser -Properties lastLogonTimestamp -Filter * -searchbase 'OU=DisabledUser,DC=federalbank,DC=co,DC=in' | select @{N='LastLogon'; E={[DateTime]::FromFileTime($.LastLogontimestamp)}},samaccountname | Where-Object {$.lastLogon -lt $DateCutOff } | foreach { Remove-ADGroupMember Office365 -Members $_.samaccountname -Confirm:$false}
I am not sure how to filter the results further for specific OU users.