2015-08-25 54 views
1

時間屬性我有這樣的查詢:PowerShell的提取可變

$cpuTime = (get-wmiobject Win32_Process -filter "commandline like '%STRING%'" -computername $server) 
$cpuTime | % { $_.ConvertToDateTime($_.CreationDate)} 

我如何提取只是 「時間」(HH,MM,SS)從$cpuTime變量?

回答

1

如果您只是想要一個字符串,可以使用custom date and time format string調用ToString。

$x = (get-wmiobject Win32_Process) 
$x | % { $creationDate = $_.ConvertToDateTime($_.CreationDate); $creationDate.ToString("hh:mm:ss")} 

你可以稱之爲DateTime.TimeOfDay獲得Timspan回來代表午夜以來經過的時間。

$x = (get-wmiobject Win32_Process) 
$x | % { $creationDate = $_.ConvertToDateTime($_.CreationDate); $creationDate.TimeOfDay} | 
Select-Object Hours, Minutes, Seconds 
+0

謝謝! 這是工作,只是爲了增加這個問題。 有沒有辦法使用這個變量來檢索進程已經運行了多長時間? –

+1

如果您在機器上擁有管理員權限,您可以獲得'KernelModeTime'和'UserModeTime',並添加它們以獲得進程一直存活的滴答總數(100ns單位)。你可以用'[TimeSpan] :: TicksPerSecond'來劃分它,以秒爲單位。 –

+1

當你開始的時候你可以做一些像'$ now =(get-date)'的事情,然後在循環中做'$ elapsed = $ now - $ creationDate'。然後,只需使用你需要的'$ elapsed'部分。 –