Users who haven’t logged in within 90 days

  Kiến thức lập trình

I want to know the user details who are all not logged on more then 90days with last logon. Also I am using Get-LastLogon function like below.
My question is : How can I write filter for $LogonDate = (Get-LastLogon -Identity $_.SamAccountName).DateTime ?

sample output :

PS C:Windowssystem32> (Get-LastLogon -Identity "user").DateTime
Wednesday, August 28, 2024 2:53:46 PM

Here is my script :

Function Get-LastLogon (){
    [cmdletbinding()]

    Param(
        [alias("UserName","User","SamAccountName","Name","DistinguishedName","UserPrincipalName","DN","UPN")]
        [parameter(ValueFromPipeline,Position=0,Mandatory)]
        [string[]]$Identity
    )

    begin{
        $DCList = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().DomainControllers.name
    }

    process{

        foreach($currentuser in $Identity)
        {
            $filter = switch -Regex ($currentuser){
                '=' {'DistinguishedName';break}
                '@' {'UserPrincipalName';break}
                ' ' {'Name';break}
                default {'SamAccountName'}
            }

            Write-Verbose "Checking lastlogon for user: $currentuser"

            foreach($DC in $DCList)
            {
                Write-Verbose "Current domain controller: $DC"
                
                $ad = [ADSI]"LDAP://$dc"

                $searcher = [DirectoryServices.DirectorySearcher]::new($ad,"($filter=$currentuser)")
                $account = $searcher.findone()
                
                if(!$account)
                {
                    Write-Verbose "No user found with search term '$filter=$currentuser'"
                    continue
                }

                $logon     = $($account.Properties.lastlogon)
                $logontimestamp = $($account.Properties.lastlogontimestamp)

                Write-Verbose "LastLogon          : $([datetime]::FromFileTime($logon))"
                Write-Verbose "LastLogonTimeStamp : $([datetime]::FromFileTime($logontimestamp))"
                
                $logontime = $($logon,$lastlogontimestamp |
                    Sort-Object -Descending | Select-Object -First 1)
            
                if($logontime -gt $newest)
                {
                    $newest = $logontime
                }
            }

            if($account)
            {
                switch ([datetime]::FromFileTime($newest)){
                    {$_.year -eq '1600'}{
                        "Never"
                    }
                    default{$_}
                }
            }

            Remove-Variable newest,account,lastlogon,logon,logontime,lastlogontimestamp -ErrorAction SilentlyContinue
        }
    }

    end{
        Remove-Variable dclist -ErrorAction SilentlyContinue
    }
}


if (-not (Get-Module ActiveDirectory)){
    Import-Module ActiveDirectory -ErrorAction Stop            
}


Get-ADUser -identity "user" -Properties * |
ForEach-Object {
    $LogonDate = (Get-LastLogon -Identity $_.SamAccountName).DateTime
    [PsCustomObject]@{
        'Account Status'  = if (($_.Enabled -eq 'TRUE')  ) {'Enabled'} Else {'Disabled'}
        'Display Name'    = $_.displayname
        'Last Logon Time' = $LogonDate

    }
}   | Export-Csv -Path 'C:tmplastlogon.csv' -NoTypeInformation -Encoding UTF8

Assuming the “get-lastlogon”cmdlet works, which looks promising, even though there might be al little problem with $newest which should be declared / set to [datetime]::MinValue once before entering the foreach($DC in $DCList) loop,
this should work in order to filter for 90-days-no-loggon-user:

   # Define the date 90 days ago from today
$cutoffDate = (Get-Date).AddDays(-90)

Get-ADUser -identity "user" -Properties * |
ForEach-Object {
    $LogonDate = (Get-LastLogon -Identity $_.SamAccountName).DateTime
    
    # Filter based on the Last Logon Time being earlier than the cutoff date
    if ($LogonDate -lt $cutoffDate) {
        [PsCustomObject]@{
            'Account Status'  = if (($_.Enabled -eq $true)) {'Enabled'} else {'Disabled'}
            'Display Name'    = $_.DisplayName
            'Last Logon Time' = $LogonDate
        }
    }
} | Export-Csv -Path 'C:tmplastlogon.csv' -NoTypeInformation -Encoding UTF8

1

You can get the list of user who have not been login their account in last 90 days.

# Define the date 90 days ago
$thresholdDate = (Get-Date).AddDays(-90)

# Get all users from Active Directory with their last logon information
$users = Get-ADUser -Filter * -Property LastLogonDate | 
         Where-Object { $_.LastLogonDate -lt $thresholdDate -and $_.Enabled -eq $true }

# Select relevant information (Username and Last Logon Date)
$report = $users | Select-Object Name, LastLogonDate

# Export the result to a CSV file
$report | Export-Csv -Path "C:PathToYourReportInactiveUsersReport.csv" -NoTypeInformation

# Display the report in PowerShell
$report

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT