Created
August 22, 2024 21:21
-
-
Save Rapidhands/3fab71fe3fe7c6b6af859e075483abbd to your computer and use it in GitHub Desktop.
Gather Computer Real LastLogon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
At the 1st DC processed, we will have all the computers and their lastLogon in a ArrayList. | |
At the following DCs processed, only the LastLogon property of the computer being processed will be updated | |
#> | |
# Gathering DCs list | |
$DCList = Get-ADDomainController -Filter * | |
# Gathering Computer List | |
$AllComputers = Get-ADComputer -Filter * | |
# Initiate a ArrayList (or Better a GenericList), cause these types of object have a method called .add() | |
$Result = [System.Collections.Generic.List[object]]::new() # or [System.Collections.ArrayList]::new() | |
ForEach ($Computer in $AllComputers) | |
{ | |
# Initializes LastLogon to $null as starting point | |
$TargetComputerLastLogon = $null | |
Foreach($DC in $DCList) | |
{ | |
Try | |
{ | |
# Retrieve the value of the lastLogon attribute from a DC (each DC in turn) | |
$LastLogonDC = Get-ADComputer -Identity $Computer.SamAccountName -Properties lastLogon -Server $DC.Name | |
# Convert value to date/time format | |
$LastLogon = [Datetime]::FromFileTime($LastLogonDC.lastLogon) | |
# If the value obtained is more recent than that contained in $TargetComputerLastLogon | |
# lthe variable is updated: this ensures to have the most recent lastLogon at the end of the processing | |
If ($LastLogon -gt $TargetComputerLastLogon) | |
{ | |
$TargetComputerLastLogon = $LastLogon | |
} | |
# Clean up var | |
Clear-Variable LastLogon | |
} | |
Catch | |
{ | |
Write-Host $_.Exception.Message -ForegroundColor Red | |
} | |
} | |
# Building a PSObject | |
$LastLogonObj = @{ | |
SamAccountName = $TargetComputer | |
LastLogon = $TargetComputerLastLogon | |
} | |
# Adding the previous PSObject to $Result | |
$Result.Add($LastLogonObj) | |
} | |
# Display the Result | |
$Result | |
# Or export in a .csv file | |
$Result | Export-Csv -Path Path\to\LastLogn.csv -NoTypeInformation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment