イベントを開始し、ユーザーが任意のキーを押してスクリプトの実行を停止するのを待つスクリプトがあります。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;
}
}