Search code examples
powershellparameter-passingjobs

Passing parameters to a PowerShell job


I've been toying around with this dang parameter passing to powershell jobs.

I need to get two variables in the script calling the job, into the job. First I tried using -ArgumentList, and then using $args[0] and $args[1] in the -ScriptBlock that I provided.

function Job-Test([string]$foo, [string]$bar){

    Start-Job -ScriptBlock {#need to use the two args in here
        } -Name "Test" -ArgumentList $foo, $bar 
}

However I realized that -ArgumentList gives these as parameters to -FilePath, so I moved the code in the scriptblock into its own script that required two parameters, and then pointed -FilePath at this script.

function Job-Test([string]$foo, [string]$bar){
    $myArray = @($foo,$bar)

Start-Job -FilePath .\Prog\august\jobScript.ps1 -Name 'Test' -ArgumentList $myArray
}

#\Prog\august\jobScript.ps1 :

Param(
    [array]$foo
    )

    #use $foo[0] and $foo[1] here

Still not working. I tried putting the info into an array and then passing only one parameter but still to know avail.

When I say no avail, I am getting the data that I need however it all seems to be compressed into the first element.

For example say I passed in the name of a file as $foo and it's path as $bar, for each method I tried, I would get args[0] as "filename path" and args[1] would be empty.

ie:

function Job-Test([string]$foo, [string]$bar){
    $myArray = @($foo,$bar)

Start-Job -FilePath .\Prog\august\jobScript.ps1 -Name 'Test' -ArgumentList $myArray
}

Then I called:

$foo = "hello.txt"
$bar = "c:\users\world"
Job-Test($foo,$bar)

I had jobScript.ps1 simply Out-File the two variables to a log on separate lines and it looked like this:

log.txt:

hello.txt c:\users\world
#(empty line)

where it should have been:

hello.txt
c:\users\world

Solution

  • you don't need to call the function like you would in java. just append the two variables to the end of the function call Job-Test $foo $bar