Get Enabled AD Users with Last Logon Time and Organizational Unit Information

This PowerShell script retrieves information about enabled Active Directory (AD) users, including their SAM account name, last logon time, and organizational unit (OU). The script makes use of several cmdlets and concepts that are common in PowerShell, including filtering, selecting, sorting, and transforming data.

Get-ADUser -Filter * -Properties lastLogon |
    Where-Object { $_.Enabled -eq $True } |
    Select-Object samaccountname, @{
        Name="lastLogon";
        Expression={[datetime]::FromFileTime($_.lastLogon)}
    }, @{
        Name="OU";
        Expression={( $_.distinguishedname -split ',' )[1].Split('=')[1]}
    } |
    Sort-Object OU |
    Where-Object { $_.OU -notmatch "CN=" }

Here is a detailed explanation of each part of the code:

  1. Get-ADUser cmdlet:

The Get-ADUser cmdlet is used to retrieve information about AD user objects. The -Filter parameter is used to specify that I want to retrieve all user objects, and the -Properties parameter is used to specify that I want to retrieve the lastLogon property.

  1. Where-Object cmdlet:

The Where-Object cmdlet is used to filter the results of the Get-ADUser cmdlet based on the Enabled property. In this case, I want to retrieve only those users that have their Enabled property set to $True.

  1. Select-Object cmdlet:

The Select-Object cmdlet is used to select specific properties from the filtered results. In this case, I want to select the samaccountnamelastLogon, and OU properties. The @{Name="lastLogon";Expression={[datetime]::FromFileTime($_.lastLogon)}} expression is used to convert the lastLogon property from a file time format to a more readable date/time format. The @{Name="OU";Expression={( $_.distinguishedname -split ',' )[1].Split('=')[1]}} expression is used to extract the name of the OU from the DistinguishedName property.

  1. Sort-Object cmdlet:

The Sort-Object cmdlet is used to sort the selected results based on the distinguishedname property. In this case, I want to sort the results in ascending order by the distinguishedname property.

  1. Where-Object cmdlet:

The final Where-Object cmdlet is used to further filter the sorted results based on the distinguishedname property. In this case, I want to retrieve only those results where the distinguishedname property does not match the string “CN=”.

Leave a Reply

Your email address will not be published. Required fields are marked *