2012-06-08 22 views
13

我有一個腳本可以啓動一個事件並等待用戶按任意鍵停止腳本執行。我試圖找到一種方法來顯示定時器(腳本運行了多長時間),同時在Read-Host上等待用戶輸入。有什麼辦法可以做到這一點?Powershell顯示已用時間

編輯:感謝所有的輸入。這工作

$Time = [System.Diagnostics.Stopwatch]::StartNew() 
while ($true) { 
    $CurrentTime = $Time.Elapsed 
    write-host $([string]::Format("`rTime: {0:d2}:{1:d2}:{2:d2}", 
     $CurrentTime.hours, 
     $CurrentTime.minutes, 
     $CurrentTime.seconds)) -nonewline 
    sleep 1 
    if ($Host.UI.RawUI.KeyAvailable -and ("q" -eq $Host.UI.RawUI.ReadKey("IncludeKeyUp,NoEcho").Character)) { 
     Write-Host "Exiting now" 
     break; 
    } 
} 
+0

看看這裏在PowerShell背景中使用WPF用戶界面http://www.nivot.org/blog/post/2008/05/23/BackgroundTimerPowerShellWPFWidget –

回答

13

從文章Measuring Elapsed Time in Powershellarchived copy):

假設變量$script:StartTime被設置在 開始你的腳本,經過時間可以使用確定以下兩種方法的 :

$elapsedTime = new-timespan $script:StartTime $(get-date)

$elapsedTime = $(get-date) - $script:StartTime

這兩種方法的工作完全一樣,併產生一個System.TimeSpan對象。

因此,使用上面的例子,你可以讀主機前設置$script:StartTime,然後調用 $elapsedTime = $(get-date) - $script:StartTime後。

+0

對,我理解的很多,但我想看看是否有可能顯示在讀主機提示符處等待時運行時鐘。 – Jeff

4

這篇文章給了我正確的觀念:

http://poshtips.com/2010/03/29/powershell-countdown-timer/

然而,使用定時器類給了我這樣的事情:

$Time = [System.Diagnostics.Stopwatch]::StartNew() 
while ($NoEvent) { 
    $CurrentTime = $Time.Elapsed 
    write-host $([string]::Format("`rTime: {0:d2}:{1:d2}:{2:d2}", 
     $CurrentTime.hours, 
     $CurrentTime.minutes, 
     $CurrentTime.seconds)) -nonewline 
    sleep 1 

    #Handle event 
    if(event){$NoEvent = false} 
} 

其中$ NoEvent爲您的活動/布爾(關鍵按功能等)。讓我知道這是否有幫助。

乾杯,

+1

diagnostics.stopwatch是越野車,fwiw – cmcginty

0

我很高興與來自Xelco52的答案

$startTime = $(get-date) 
write-host "Elapsed:00:00:00" 
$NoEvent = $true 
While ($NoEvent) 
{ 
    Start-Sleep 1 
    $elapsedTime = new-timespan $startTime $(get-date) 
    write-host "Elapsed:$($elapsedTime.ToString("hh\:mm\:ss"))" 

    #Handle event 
    if(event){$NoEvent = $false} 
} 
-1

這擴大了這個小功能給我的輸出,我是後:)

$StartTime = $(get-date) 

$elapsedTime = $(get-date) - $StartTime 

$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks) 
相關問題