Created
June 11, 2019 01:17
-
-
Save fgervais/9f05b18b06242292e50f2792d9b29c82 to your computer and use it in GitHub Desktop.
Powershell execute a function with a timeout
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 Install($param1, $param2) { | |
Start-Sleep -s 2 | |
echo "Installing $param1 $param2" | |
} | |
function Execute-With-Timeout($function, $timeout_sec) { | |
$job = $function & | |
$start_time = Get-Date | |
while ($job.State -ne "Completed") { | |
Start-Sleep -s 1 | |
if (((Get-Date) - $start_time).TotalSeconds -gt $timeout_sec) { | |
break | |
} | |
} | |
echo $job.State | |
if ($job.State -ne "Completed") { | |
echo "Timeout!" | |
Remove-Job -Force $job | |
throw "Timeout" | |
} | |
} | |
try { | |
Execute-With-Timeout -function { Install "one" "two" } -timeout 1 | |
} | |
catch { | |
echo "Something went wrong" | |
} | |
finally { | |
echo "Releasing ressources" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment