Skip to content

Instantly share code, notes, and snippets.

@scriptingstudio
Last active May 2, 2025 08:11
Show Gist options
  • Select an option

  • Save scriptingstudio/9d50c6d728d490eea6694af71514681a to your computer and use it in GitHub Desktop.

Select an option

Save scriptingstudio/9d50c6d728d490eea6694af71514681a to your computer and use it in GitHub Desktop.
Simple await function to wait for an async task to complete within timeout and return the result if any
function Wait-Task {
param (
[Parameter(Mandatory, ValueFromPipeline)]
[System.Threading.Tasks.Task] $Task,
[alias('wait')][int] $TimeOutMs = 1000
)
begin {if ($TimeOutMs -lt 1) {$TimeOutMs = -1}}
process {
if ($task.AsyncWaitHandle.WaitOne($timeoutMs)) {
$task.GetAwaiter().GetResult()
}
}
} # END Wait-Task
filter Wait-Task ([alias('wait')][int]$TimeOutMs = 1000) {
if ($timeoutMs -lt 1) {$timeoutMs = -1}
if ($_.AsyncWaitHandle.WaitOne($timeoutMs)) {$_.GetAwaiter().GetResult()}
} # END Wait-Task
# example
$webclient = [System.Net.Webclient]::New()
$webclient.DownloadStringTaskAsync('https://docs.microsoft.com/en-us/windows/release-health/windows11-release-information') |
Wait-Task -wait 400
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment