Following the post about the Defender status report in PowerShell, I decided to create a script that will generate a list of servers based on Active Directory data, just like in the previous case, and gather information about the current UpTime and last boot time.
In the first step, we need to retrieve a list of computers or servers. If we have this list in a file, we can use it. However, I am obtaining the list of machines from Active Directory.
1 2 |
$ComputerList=Get-ADComputer -SearchBase "OU=Servers,OU=company,DC=domain,DC=local" -Filter 'enabled -eq "true"' | Select-Object -ExpandProperty Name $ComputerList.Count |
The variable $ComputerList will contain all the hosts to be checked.
Now, I will present the code that checks each host from the list and queries for uptime. As in the previous post, I’ve also implemented a safeguard to ensure that unreachable hosts are not included in the final report.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$UptimeReport = @() foreach ($comp in $ComputerList) { $i++ if(Test-Connection -ComputerName $comp -Count 1){ try{ $LastBoot=(Get-CimInstance -ClassName win32_operatingsystem -ComputerName $comp -ErrorAction Stop).LastBootUpTime If ($LastBoot) { $Uptime = (Get-Date) - $LastBoot $UptimeReport+=New-Object -TypeName PSObject -Property ([ordered]@{ "Computer Name"= $comp "LastBootUp" = $LastBoot "UpTime [HH:MM:SS]"=-join($Uptime.Days,":",$Uptime.Hours,":",$Uptime.Minutes) }) } }catch{} } } $UptimeReport | Format-Table -AutoSize |
After the script has executed, the results will be displayed in a table: