Skip to content

Instantly share code, notes, and snippets.

@fgervais
Created June 11, 2019 01:17
Show Gist options
  • Save fgervais/9f05b18b06242292e50f2792d9b29c82 to your computer and use it in GitHub Desktop.
Save fgervais/9f05b18b06242292e50f2792d9b29c82 to your computer and use it in GitHub Desktop.
Powershell execute a function with a timeout
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