Reputation: 45
I'm trying to use PowerShell to get and show the last Bootup time of different systems. In testing the code, I'm not getting any results at all. Currently, my code is as follows:
$Servers = Get-Content "\\File Path\Server Restarts\Server List.txt"
Write-Host "---Servers Currently On List---"
$i = 1
ForEach ($Server in $Servers)
{
Write-Host "$i) $Server"
$i++
}
$Server = Read-Host -Prompt "HOST NAME OR IP"
$LastBoot = (Get-CimInstance Win32_OperatingSystem -ComputerName $Server -EA 0).LastBootUpTime
Write-Host "Last Bootup time of $Server is: $LastBoot"
Currently, the script spits out nothing for $LastBoot
. As the script exists right now, I'm not sure if it's even grabbing the info I'm trying to grab.
Upvotes: 0
Views: 55
Reputation: 61198
As commented, you need to test if any of the servers in the list is reachable before trying to output something.
I would also suggest you output objects instead of plain text to make it easier to format on screen and also easy enough to export the data to a CSV file
Try:
$result = Get-Content -Path "\\File Path\Server Restarts\Server List.txt" | ForEach-Object {
# create an object to output
$out = $_ | Select-Object @{Name = 'Server'; Expression ={$_}}, Status, LastBootUpTime
if (Test-Connection -ComputerName $_ -Count 1 -Quiet) {
$out.Status = 'OK'
$out.LastBootUpTime = (Get-CimInstance Win32_OperatingSystem -ComputerName $_).LastBootUpTime
}
else {
$out.Status = 'OffLine'
}
$out
}
$result | Format-Table -AutoSize
# and/or if you want, output to a CSV file you can double-click to open in Excel
$result | Export-Csv -Path 'C:\SomePath\ServerLastBootUpTimes.csv' -NoTypeInformation -UseCulture
Or do
$result = Get-Content -Path "\\File Path\Server Restarts\Server List.txt" | ForEach-Object {
# create an object to output
$out = $_ | Select-Object @{Name = 'Server'; Expression ={$_}}, Status, LastBootUpTime
$server = Get-CimInstance Win32_OperatingSystem -ComputerName $_ -ErrorAction SilentlyContinue
if ($server) {
$out.Status = 'OK'
$out.LastBootUpTime = $server.LastBootUpTime
}
else {
$out.Status = 'OffLine'
}
$out
}
$result | Format-Table -AutoSize
# and/or if you want, output to a CSV file you can double-click to open in Excel
$result | Export-Csv -Path 'C:\SomePath\ServerLastBootUpTimes.csv' -NoTypeInformation -UseCulture
Upvotes: 1