Powershell pass variable to start-job

jjamesjohnson picture jjamesjohnson · Apr 9, 2012 · Viewed 41.7k times · Source

within powershell I'd like to learn the best way to call a variable to a start job so I don't have to edit the script for each server as it will be specific based on the client I've placed my script on.

$Servername = 'Server1'
    $pingblock = {
      pathping $servername | Out-File C:\client\PS\ServerPing.TXT
    }
    start-job $pingblock

when I run my code above I just get a file with the help as if I forgot the specify the $servername.

Answer

Keith Hill picture Keith Hill · Apr 9, 2012

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