2012-06-08 19 views
13

Tengo un script que inicia un evento y espera a que el usuario presione cualquier tecla para detener la ejecución del script. Estaba intentando encontrar una manera de mostrar un temporizador (cuánto tiempo ha estado ejecutándose el script) mientras esperaba la entrada del usuario en Read-Host. ¿Hay alguna forma de lograr esto?Powershell mostrar el tiempo transcurrido

Editar: Gracias por toda la aportación. Esto funciona

$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

Echa un vistazo aquí para usar la interfaz de usuario de WPF en backgound en powershell http://www.nivot.org/blog/post/2008/05/23/BackgroundTimerPowerShellWPFWidget –

Respuesta

13

Desde el artículo Measuring Elapsed Time in Powershell (archived copy):

Suponiendo que la variable $script:StartTime se fijó en el comienzo de su script, el tiempo transcurrido puede ser determinado utilizando de los métodos siguientes :

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

o

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

Ambos métodos funcionan exactamente de la misma y producen un objeto System.TimeSpan.

Así, usando el ejemplo anterior, podría configurar $script:StartTime antes de Read-Host y luego llamar $elapsedTime = $(get-date) - $script:StartTime después.

+0

Correcto, eso sí lo entiendo, pero quería ver si es posible mostrar un reloj en funcionamiento mientras espera en el prompt Read-Host. – Jeff

4

Este artículo me dio la idea correcta:

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

Sin embargo, el uso de la clase temporizador me dio algo como esto:

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

Donde $ noEvent es su evento/booleano (clave presione func, etc.). Déjeme saber si esto ayuda.

Cheers,

+1

diagnostics.stopwatch tiene errores, fwiw – cmcginty

0

estoy feliz con esta pequeña función ampliada desde la respuesta de 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

esto me dio la salida que estaba buscando :)

$StartTime = $(get-date) 

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

$totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks) 
Cuestiones relacionadas