Await async C# method from PowerShell
It'll run fine on its own, but if you want to wait for it to finish you can use this
$null = [MyNamespace.MyClass]::MyStaticMethod($myParam).GetAwaiter().GetResult()
This will unwrap the AggregateException
that would be thrown if you used something like $task.Result
instead.
However that will block until it's complete, which will prevent CTRL + C
from properly stopping the pipeline. You can wait for it to finish while still obeying pipeline stops like this
$task = [MyNamespace.MyClass]::MyStaticMethod($myParam)
while (-not $task.AsyncWaitHandle.WaitOne(200)) { }
$null = $task.GetAwaiter().GetResult()
If the async method actually returns something, remove $null =
Borrowing from Patrick Meinecke's answer, it's possible to make a pipeline-able function that will resolve a task (or list of tasks) for you:
function Await-Task {
param (
[Parameter(ValueFromPipeline=$true, Mandatory=$true)]
$task
)
process {
while (-not $task.AsyncWaitHandle.WaitOne(200)) { }
$task.GetAwaiter().GetResult()
}
}
Usage:
$results = Get-SomeTasks $paramA $paramB | Await-Task