I'm attempting to learn how to use a runspace in Powershell. I've been able to integrate most of my code, but the line beginning with XML below has given me trouble in the snippet below:
When I set $Report within the ForEach and add the argument to the runspace I'm able to get my desired results. I'd rather the report be generated within the scriptblock. When the line is run within the scriptblock $Report has a value for the first thread, but not for subsequent threads. Other variables set within the scriptblock end up in the results without issue (ran a test generating a new variable that pulled $GPO.DisplayName and a random number to monitor whether data was being changed or not).
Would anyone be able to shed some light on what I could do to have the xml report generated within the scriptblock? I saw some warnings that threads could share variables, but did not locate further information to explain how that works or how to avoid the scenario.
Code:
$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $Throttle)
$RunspacePool.Open()
$Jobs = @()
ForEach ($GPO in $GPOList) {
# Create an XML report of the GPO that can be used to query for information.
$Report = $Null
[XML]$Report = Get-GPOReport -GUID $GPO.ID -ReportType XML
$Job = [Powershell]::Create().AddScript($ScriptBlock).AddArgument($GPO).AddArgument($LinkedGPOIDs).AddArgument($Report)
$Job.RunspacePool = $RunspacePool
$Jobs += New-Object PSObject -Property @{
Pipe = $Job
Result = $Job.BeginInvoke()
}
}
When I set $Report within the ForEach and add the argument to the runspace I'm able to get my desired results. I'd rather the report be generated within the scriptblock. When the line is run within the scriptblock $Report has a value for the first thread, but not for subsequent threads. Other variables set within the scriptblock end up in the results without issue (ran a test generating a new variable that pulled $GPO.DisplayName and a random number to monitor whether data was being changed or not).
Would anyone be able to shed some light on what I could do to have the xml report generated within the scriptblock? I saw some warnings that threads could share variables, but did not locate further information to explain how that works or how to avoid the scenario.