Link to home
Start Free TrialLog in
Avatar of SAM IT
SAM IT

asked on

sort-object -descending the lastlogondate

Below mentioned script fine. I am trying to sort-object -descending the lastlogondate but output not getting as expected, getting output in  generic   .

Can any one assist to sort the lastlogondate in to – descending.

Thanks in advance


$DCs = 'DC01','DC02'

$ADObjects = @{}
ForEach ($DC in $DCs) {
	Write-Host "Processing logons at $($DC) ..."
	Get-ADComputer -Filter * -Property lastLogon -SearchBase "DC=test,DC=com" -Server $DC | ForEach-Object {
		If ($ADObjects.ContainsKey($_.SamAccountName)) {
			If ($ADObjects[$_.SamAccountName].LastLogon -lt $_.lastLogon) {
				$ADObjects[$_.SamAccountName].LastLogon = $_.lastLogon
				$ADObjects[$_.SamAccountName].LastLogonAt = $DC
			}
		} Else {
			$ADObjects.Add($_.SamAccountName, ($_ | Select-Object SamAccountName, Name, LastLogon, @{Name='LastLogonAt'; Expression={$DC}}))
		}
	}
}
$ADObjects.Values |
	Sort-Object Name, SamAccountName, @{Name='Last Logon Date'; Expression={If ($_.lastLogon) {[datetime]::FromFileTime($_.lastLogon)} Else {'None'}}}, LastLogonAt |
	Export-CSV C:\temp\LastLogonReport.csv -NoTypeInformation

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SAM IT
SAM IT

ASKER

thanks OBDA.

One more question : -

I have 05 Domain controllers , On each domain controller 1000 AD computer objects are there , I have executed the script and got the output aproximatly 5k AD computer objects.

Means for one AD computer object there will be an 5 entries on the output, Out of 05 entries for each AD computer I have to remove 4 entries and remain 01 entry that should be the latest one .

The resaon behind I have requested for assistance for -desending is to give a try to get the timestamp of object with the latest one & finding the soultion to remove the rest 04 old entries.

Any suguesstions please
Avatar of SAM IT

ASKER

any possible way that putting condition saying keep latest timestamp for each adcomputer object and remove rest of the entries or any other suggestions