你可以只使用TimeSpan對象對ToString
方法,並指定要使用的格式。請使用standard timespan formats之一或使用custom timespan format。例如,下面的自定義格式給你想要的輸出:
$ts = [timespan]::fromseconds("7000.6789")
$ts.ToString("hh\:mm\:ss\,fff")
這將輸出
01:56:40,679
更新:更新到提供的PowerShell V2
上述解決方案工程工作職能以及在PowerShell v4中,但不在v2中(因爲直到.NET Framework 4才添加TimeSpan.ToString(string)
方法)。
在v2中,我想你必須手動創建字符串(就像你在做問題)或者做一個普通的ToString()
並操縱字符串。我建議前者。下面是其爲正常工作的功能:使用
$ts = [timespan]::fromseconds("7000.6789")
Format-TimeSpan -TimeSpan $ts
$ts | Format-TimeSpan
它
function Format-TimeSpan
{
PARAM (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[TimeSpan]$TimeSpan
)
#Current implementation doesn't handle days.
#By including the delimiters in the formatting string it's easier when we contatenate in the end
$hours = $TimeSpan.Hours.ToString("00")
$minutes = $TimeSpan.Minutes.ToString("\:00")
$seconds = $TimeSpan.Seconds.ToString("\:00")
$milliseconds = $TimeSpan.Milliseconds.ToString("\,000")
Write-Output ($hours + $minutes + $seconds + $milliseconds)
}
測試產生以下的輸出:
01:56:40,679
01:56:40,679
'$ res.ToString()'是否滿足您的要求?如果沒有相關數字,它會跳過毫秒,如果小時數高於23,它會附加日期,這可能不適合您。如果這不起作用,請查看採用格式字符串的'TimeSpan.ToString(string)'方法。格式字符串可以是[標準時間段格式](http://msdn.microsoft.com/zh-cn/library/ee372286(v = vs.110).aspx)或[自定義時間段格式](http: //msdn.microsoft.com/en-us/library/ee372287(v=vs.110).aspx)。 –