Filter for OU from a Groupmembership

Varughese Kochukalical Eappen 21 Reputation points
2022-04-13T10:07:21.747+00:00

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.

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
5,899 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Newbie Jones 1,306 Reputation points
    2022-04-13T14:04:52.923+00:00

    You can do this by updating the Where-Object client side filter.

    You currently have...

    Where-Object {$.lastLogon -lt $DateCutOff }

    Try the following..

    Where-Object {$.lastLogon -lt $DateCutOff -and $_.DistinguishedName -notlike "*OU=skip,OU=example,DC=example,DC=com"}

    0 comments No comments

  2. Newbie Jones 1,306 Reputation points
    2022-04-13T14:09:17.947+00:00

    The Where-Object client side filter should probably be before the select statement where you drop any extraneous attributes. DistinguishedName is part of the default attributes for Get-ADUser and you need this for the filter to work.

    On a side note, you can't really use lastLogon like that.

    LastLogin is not a replicated attribute, which means it can be different based on the domain controller that services that request. Therefore in order to get an accurate lastLogon, you need to query all of the domain controllers and get the newest date.


  3. Newbie Jones 1,306 Reputation points
    2022-04-13T14:13:11.26+00:00

    Here is a function you can use for LastLogon with a example.

    Function Get-LastLogon {
        <#
        .SYNOPSIS
        Returns LastLogon information
        .DESCRIPTION
        Queries the LastLogin information for a user across domain controllers and returns the highest (latest) value
        .EXAMPLE
        Get-LastLogon User
        .EXAMPLE
        Get-LastLogon -Identity User
        .EXAMPLE
        Get-ADUser User | Get-LastLogon
        .EXAMPLE
        Get-LastLogon User1, User2
        .PARAMETER users
        List of users - pipeline can be used
        #>
    
        [CmdletBinding()]
        param
        (
        [Parameter(Position= 0,
                    Mandatory=$True,
                        ValueFromPipeline=$True,
                            HelpMessage='What user would you like to find the last logon for?')]
        $identity
        )
    
        Begin {}
    
        Process {
    
            Foreach ($account in $identity) {
    
                $dateStamp = $null
                $domainController =$null
    
                # Using Filter to remove Azure domain controllers
                Get-ADDomainController -Filter {Site -eq "xyz"} | Foreach {
    
                    $dc = $_.HostName
    
                    $lastLogon = (Get-ADUser $account -Properties LastLogon -server $dc | Select-Object Name,@{n='LastLogon';e={[DateTime]::FromFileTime($_.LastLogon)}}).Lastlogon
    
                    If ($dateStamp -le $lastlogon)
                        {
                        $dateStamp = $lastlogon
                        $domainController = $dc
                        }
    
                } # End of ForEach
    
                $properties = @{
                Name=$account;
                LastLogon=$dateStamp;
                DomainController=$domainController}
    
                New-Object -TypeName PSObject -Prop $properties
    
            } # End of ForEach
    
        } # End of Process
    
        End {}          
    
    } # End of Function
    
    $list = IMPORT-CSV 'users.csv'
    $list | ForEach {
        Get-ADUser $_.SamAccountName | Get-LastLogon | Select-Object Name, Lastlogon 
    } | Export-CSV LastLogon.csv -NoTypeInformation
    
    0 comments No comments