Created
November 15, 2013 00:02
-
-
Save mwrock/7476703 to your computer and use it in GitHub Desktop.
while waiting for the scheduled task to finish
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Wait-ForTask($waitProc, $idleTimeout, $totalTimeout){ | |
$reader=New-Object -TypeName System.IO.FileStream -ArgumentList @( | |
"$env:temp\BoxstarterOutput.Stream", | |
[system.io.filemode]::Open,[System.io.FileAccess]::ReadWrite, | |
[System.IO.FileShare]::ReadWrite) | |
try{ | |
$procStartTime = $waitProc.StartTime | |
while($waitProc -ne $null -and !($waitProc.HasExited)) { | |
$timeTaken = [DateTime]::Now.Subtract($procStartTime) | |
if($totalTimeout -gt 0 -and $timeTaken.TotalSeconds -gt $totalTimeout){ | |
Write-BoxstarterMessage "Task has exceeded its total timeout. Killing task..." | |
KillTree $waitProc.ID | |
throw "TASK:`r`n$command`r`n`r`nIs likely in a hung state." | |
} | |
$byte = New-Object Byte[] 100 | |
$count=$reader.Read($byte,0,100) | |
if($count -ne 0){ | |
$text = [System.Text.Encoding]::Default.GetString($byte,0,$count) | |
$text | Out-File $boxstarter.Log -append | |
$text | write-host -NoNewline | |
} | |
else { | |
Test-TaskTimeout $waitProc $idleTimeout | |
} | |
} | |
Start-Sleep -Second 1 | |
Write-Debug "Proc has exited: $($waitProc.HasExited) or Is Null: $($waitProc -eq $null)" | |
$byte=$reader.ReadByte() | |
$text=$null | |
while($byte -ne -1){ | |
$text += [System.Text.Encoding]::Default.GetString($byte) | |
$byte=$reader.ReadByte() | |
} | |
if($text -ne $null){ | |
$text | out-file $boxstarter.Log -append | |
$text | write-host -NoNewline | |
} | |
} | |
finally{ | |
if($waitProc -ne $null -and !$waitProc.HasExited){ | |
KillTree $waitProc.ID | |
} | |
$reader.Dispose() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment