Ok, thanks to @Santiago Squarzon I discovered the benefits of a runspace.
If anyone is interested, you can improve a bit and add an object of type System.Management.Automation.PSDataCollection[psobject] to inspect whatever is in the pipeline of the runspace, while iasync is still running. Like so:
$Inspector= new-object 'System.Management.Automation.PSDataCollection[psobject]'
$iasync = $ps.BeginInvoke($Inspector,$Inspector)
More details here:
https://learn-powershell.net/2016/02/14/another-way-to-get-output-from-a-powershell-runspace/
And when typing $Inspector you get the results, but bare in mind that by doing so, you're trapped in this runspace until it ends (in my case it is never).
In my case, involving $ps.BeginStop($null, $null)
didn't stop the iasync object from running
The only way to stop it cleanly was to use $Session.Abort()
(This is a WinSCP session).
Every .Dispose()
I tried to execute, like $PS.Dispose(), $RunSpace.Dispose(), while $iasync was running, resulted in a script-hang.
I wonder what other actions are able to force-complete iasync (or AsyncObject in my case) and terminate the WinSCP session.
Assigning $null to $PS, $RunSpace, $iasync didn't stop the WinSCP session. Let's say, .Abort()
wasn't available, is $Session=$null a smart move??
Here's my final code:
$ParameterList=@{
Session= $Session
SessionOptions=$SessionOptions
}
$RunSpace= [runspacefactory]::CreateRunspace()
$PS= [powershell]::Create()
$PS.RunSpace= $RunSpace
$RunSpace.Open()
$null= $PS.AddScript({
Param($Session,$SessionOptions)
$Session.Open($SessionOptions)
}).AddParameters($ParameterList)
# Using the optional inspector object
$Inspector= new-object 'System.Management.Automation.PSDataCollection[psobject]'
$AsyncObject= $PS.BeginInvoke($Inspector,$Inspector)
#$AsyncObject= $PS.BeginInvoke()
$StartTime= Get-Date
Do{
# Timer for 10 seconds
}While ((([DateTime]::Now)-$StartTime).Seconds -lt 10)
If ($AsyncObject.IsCompleted -ne "True"){
write-host "$($Session.Output)"
write-host "`n`nAborting"
$Session.Abort()
$Session.Dispose()
$Inspector.Dispose()
$PS.Dispose()
}