New PowerShell Program
So the other day I was at work and was wondering if there was a way to check all the PC's on the network and find out when the last time they were active.
I then began to write something in PowerShell. I also wanted the Computer name and the last user who was logged into the PC. Just to make a list of older PCs on the network, and users we need to clean up in AD.
Using AD, I could get most of the information I needed, and then using SSH to reach out to every PC and update the latest information. How it would work is it would ping the pc to see if it was active, then using SSH to get the information I wanted. I also wanted it to be placed into a spreadsheet to be able to send it to the Sys Admins.
Now, to use this, you will need to run PowerShell as an administrator.
Here is the code
$computers = Get-ADComputer -Filter * -Property Name, LastLogonTimestamp
$results = @()
foreach ($computer in $computers) { $compName = $computer.Name $lastLogon =[DateTime]::FromFileTime($computer.LastLogonTimestamp)
Write-Host "Checking $compName..." -ForegroundColor Cyan
# Set a default value
$lastUser = "Unknown or Offline"
# Try to ping and connect if the machine is online
if (Test-Connection -ComputerName $compName -Count 1 -Quiet) { try {
# Try to grab the last logged-on user
$sysInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $compName
$lastUser = $sysInfo.UserName $model = $sysInfo.Model } catch { $lastUser = "Access Denied" } } else { $lastUser = "Offline" }
$results += [PSCustomObject]@{ ComputerName = $compName LastLogonToAD = $lastLogon LastLoggedInUser = $lastUser SystemModel = $model } }
Display
$results | Sort-Object LastLogonToAD -Descending | Format-Table -AutoSize
Optional: export to CSV
$desktop = [Environment]::GetFolderPath("Desktop") $path = Join-Path -Path $desktop -ChildPath "PC_LastLogonAndUser.xlsx"
$results | Export-Excel -Path $path -AutoSize -BoldTopRow -Title "PC Last Logon and User Report" -WorksheetName "Report"











