I have a PowerShell script where I want to create a background thread and dynamically exchange data with my primary thread. The idea was to use the information stream since it can handle all kind of objects easily.
Usually I do so by giving the PowerShell-Object to itself like the following:
$Code =
{
Param($Me)
#Here I can use $Me.Streams.Information to exchange data any time,
#for example to feed my thread with more work to do on the fly
$ResultData = [System.Object[]]::new(0)
$WorkCounter = 0
$Finished = $false
while (-not $Finished)
{
while ($Me.Streams.Information.Count -eq $WorkCounter)
{
#Wait for data to be added to the information stream
Sleep -MilliSeconds 10
}
$InputData = $Me.Streams.Information[-1].MessageData
if ($InputData -eq "FINISHED")
{
$Finished = $true
}
else
{
<# Do some stuff with the $InputData #>
$ResultData += $ProgressedInputData
}
$WorkCounter++
}
Write-Information $ResultData
}
$PS = [PowerShell]::Create()
$PS.AddScript($Code) | Out-Null
$PS.AddArgument($PS) | Out-Null #Hand the PS to itself to make the streams accessible inside the thread
$Handle = $PS.BeginInvoke() | Out-Null
for ($i = 0; $i -lt 10; $i++)
{
$PS.Streams.Information.Add([System.Management.Automation.InformationRecord]::new($i, ""))
#I just gave my background thread some stuff to do without the need to instantiate a new one again
#Now this thread can do some work too...
}
$PS.Streams.Information.Add([System.Management.Automation.InformationRecord]::new("FINISHED", ""))
$Handle.AsyncWaitHandle.WaitOne() #Wait for my background thread to finish all its work
$SomeReturnValue = $PS.Streams.Information[-1].MessageData
My actual question is: Is it possible, to access the current PowerShell instance without the need to hand it over like I did with $PS.AddArgument($PS)?