Powershell pass variable to start-job Powershell pass variable to start-job powershell powershell

Powershell pass variable to start-job


Use the -ArgumentList parameter on Start-Job e.g.:

Start-Job -Scriptblock {param($p) "`$p is $p"} -Arg 'Server1'

In your case:

$pingblock = {param($servername) pathping $servername | Out-File C:\...\ServerPing.txt}Start-Job $pingblock -Arg Server1


To complement Keith Hill's helpful answer with a PSv3+ alternative:

The $using: scope modifier can be used to reference the values of variables in the caller's scope inside the script block passed to Start-Job, as an alternative to passing arguments (by default, a script block executed as a background job does not see any of the caller's variables or other definitions):

$Servername = 'Server1'Start-Job { "Target: " + $using:ServerName } | Receive-Job -Wait -AutoRemoveJob

The above yields:

Target: Server1

Note that the same technique can be used when passing a script block for execution on a remote computer to Invoke-Command - see this question.