28

イベントを開始し、ユーザーが任意のキーを押してスクリプトの実行を停止するのを待つスクリプトがあります。Read-Hostでユーザー入力を待っている間に、タイマー (スクリプトが実行されている時間) を表示する方法を見つけようとしていました。これを達成する方法はありますか?


これは機能します

$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;
    }
}
4

4 に答える 4

28

これにより、私が求めていた出力が得られました:)

$StartTime = $(get-date)

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

$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks)
于 2017-07-11T10:02:05.690 に答える
19

Powershell での経過時間の測定(アーカイブ コピー)の記事から:

変数$script:StartTimeがスクリプトの最初に設定されていると仮定すると、経過時間は次のいずれかの方法を使用して決定できます。

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

また

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

どちらのメソッドもまったく同じように機能し、System.TimeSpanオブジェクトを生成します。

$script:StartTimeしたがって、上記の例を使用すると、Read-Host の前に 設定してから呼び出すことができます$elapsedTime = $(get-date) - $script:StartTime

于 2012-06-08T00:44:19.227 に答える
7

タイマークラス(RIP poshtips)を使用すると、次のようになります。

$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は、イベント/ブール値(キーを押す関数など)です。

于 2012-06-08T13:28:41.327 に答える