Rawns
Rawns

Reputation: 875

How to format output to DD, HH, MM

I'm trying to work out a devices up time using PowerShell. My code is as so:

$wmi = Get-WmiObject -Class Win32_OperatingSystem
$upTime = $wmi.ConvertToDateTime($wmi.LocalDateTime) – $wmi.ConvertToDateTime($wmi.LastBootUpTime)

When I call $upTime, it returns the following:

Days              : 0
Hours             : 1
Minutes           : 8
Seconds           : 5
Milliseconds      : 311
Ticks             : 40853110010
TotalDays         : 0.0472836921412037
TotalHours        : 1.13480861138889
TotalMinutes      : 68.0885166833333
TotalSeconds      : 4085.311001
TotalMilliseconds : 4085311.001

While I can see the up time, I need to specifically format the output to D:dd, H:hh, M:mm as I will be automatically feeding this into a monitoring system, but after much searching on here, google etc, I can't see how to achieve this. Can anyone suggest how to go about doing this?

Upvotes: 2

Views: 498

Answers (2)

MrX
MrX

Reputation: 66

You can format it in normal .NET style

$UptimeStr = $Uptime.ToString("ddd:dd, H:hh, mmm:mm")

or

$UptimeStr = '{0:ddd:dd, H:hh, mmm:mm}' -f $Uptime

If the above formatting is not what you wanted the formatting is explained on MSDN

Upvotes: -1

Richard
Richard

Reputation: 7000

Try:

"D:{0:dd}, H:{0:hh}, M:{0:mm}" -f $upTime

alternatively, if you like to escape lots of things:

$upTime.ToString('\D\:dd\,\ \H\:hh\,\ \M\:mm')

This will format the string to have 2 leading zeros when ether days, hours or seconds is 0. And 1 leading zero if they are 1-9.

"D:01, H:02, M:23"

Upvotes: 3

Related Questions