As you may be aware, we posted Practice Events for the 2013 Scripting Games, in an effort to give people an idea of what the events would look like and involve. There's been a lively discussion in the PowerShell.org forums about the Beginner Practice, so I thought I'd weigh in. Here's my solution:
Of course, that's hardly the only way to go about it. I used this approach because it minimizes the use of extra variables, and doesn't create a script-style approach - it's a "one-liner," although I've broken it across several physical lines for readability. I think it makes good use of PowerShell's native ability to deal with multiple objects in a stream - there's no need for a ForEach loop, here.
There’s been some discussion on that thread about how the calculation needs to be made for hours. I’d assumed that you’d need to use (and truncate) the TotalHours, or you would lose reporting on any whole days of uptime.
I used the following to convert the days into hours and add it to hours:
Get-WmiObject -ComputerName (get-content “servers.txt”) -Class Win32_OperatingSystem |
Select-Object @{n=”ComputerName”;e={$_.__SERVER}}, @{n=”Uptime”;e={(Get-Date) – $_.ConverttoDateTime($_.LastBootUpTime)}} |
Select-Object ComputerName, @{n=”Hours”;e={(($_.Uptime).Days * 24) + (($_.Uptime).Hours)}},
@{n=”Minutes”;e={(($_.Uptime).Minutes)}},
@{n=”Seconds”;e={(($_.Uptime).Seconds)}}
I decided to use “Uptime” as the variable in the second part of the pipeline to make the days to hours calculation a little easier to write