Before we get into the function let’s address the gotcha. I learned about a new parameter to Start-Job in Event #5 this year, ArgumentList. If you look at the documentation on this parameter it is a little bit misleading. I’ve filed a documentation bug on connect should you wish to vote for it. The short of it is, even though the parameter help doesn’t mention that the ArgumentList parameter works with the ScriptBlock parameter, it does. Which is pretty important. To illustrate this, try the following:
- Create a variable
$arr = 1..5 - Start a background job that writes that variable to output
$job = Start-Job –Scriptblock { Write-Output $arr } - Receive the job
Receive-Job $job - Notice that there is no output, sadface.
Important: Background jobs that are started by using Start-Job or the AsJob parameter of Invoke-Command rely on the Windows PowerShell remoting infrastructure. To use these features, Windows PowerShell must be configured for remoting, even if the background job is run only on the local computer. For more information, see about_Remote_Requirements.The second from Get-Help about_scopes:
Sessions: A session is an environment in which Windows PowerShell runs. When you create a session on a remote computer, Windows PowerShell establishes a persistent connection to the remote computer. The persistent connection lets you use the session for multiple related commands.Aha! The variable scope is separate and distinct inside of the scriptblock that we pass to Start-Job. So we use the ArgumentList parameter to get the information that we need to the scriptblock. Let’s see that in action:
Because a session is a contained environment, it has its own scope, but a session is not a child scope of the session in which is was created. The session starts with its own global scope. This scope is independent of the global scope of the session. You can create child scopes in the session. For example, you can run a script to create a child scope in a session.
- Create a variable:
$arr = 1..5 - Start a background job, passing the variable as an argument:
$job = Start-Job –Scriptblock { Write-Output $args } –ArgumentList $arr - Receive the job
Receive-Job $job - Hey there’s our information!
Get the function here.