2

Using Start-Job and ArgumentList, how do you pass an array and another variable to the receiving script?

This works if I only need to pass a single array

Start-Job -FilePath "c:\thescript.ps1" -ArgumentList (,$newArray)

Tried this, but the second value is not being used in the receiving script.

Start-Job -FilePath "c:\thescript.ps1" -ArgumentList (,$newArray,"x") 

thescript.ps1 example:

param (
    [string[]]$aMyArray,
    [string]$sMyString
)

function DoWork ([string]$aItem,[string]$sMyString)
{
    #worker
}

foreach($aItem in $aMyArray)
{
    DoWork $aItem $sMyString
}

I'm currently working in PowerShell 2.0

Taco_Buffet
  • 227
  • 1
  • 2
  • 16
  • 3
    take the x out of the brackets. You don't use commas to delimit arguments. They are seen as a single object otherwise. – Matt Jun 16 '17 at 17:16
  • @Matt this is what you are suggesting? -ArgumentList (,$newArray) "x" – Taco_Buffet Jun 16 '17 at 18:27
  • Yes. It all depends on your use case and how thescript.ps1 is configured though. – Matt Jun 16 '17 at 18:45
  • @Briantist. He knows how to pass the array. Its the next arguments he is having an issue with. I was looking for a multiple arguments dupe but didnt find one i liked. – Matt Jun 16 '17 at 18:50
  • @Matt I see you're correct; reopened. – briantist Jun 16 '17 at 18:52
  • @Matt I've updated the post to include an example of thescrpit.ps1. You see anything that would stop the second argument from being passed in? – Taco_Buffet Jun 19 '17 at 18:21

2 Answers2

2

Just googled the same question but in the end I figured out. It's rather straight forward. Though in all posts the solution to pass an array to a job is (,$ArrayArg) and it works (for me it's still weird) if that is the only argument. Though with multiple args, one being an array, this is what worked for me:

$foo1 = @("1","2","3")
$foo2 = "foo"

Start-Job -Name Test `
-ScriptBlock {
    param([string[]]$arg1,[string]$arg2)
    Write-Output $arg1
    Write-Output $arg1.GetType()
    Write-Output "----"
    Write-Output $arg2
    Write-Output $arg2.GetType()
} `
-ArgumentList @($foo1),$foo2
Christopher G. Lewis
  • 4,777
  • 1
  • 27
  • 46
cgsilver
  • 29
  • 3
0

I have to do it this way with the comma and parentheses around $list:

$list = echo a b c 

Start-Job -ScriptBlock {
  param ( $a )

  $a | % { $_ }
} -Args (,$list) | Wait-Job | Receive-Job

Or with the using scope:

$list = echo a b c

Start-Job -ScriptBlock {
  $using:list | % { $_ }
} | Wait-Job | Receive-Job
js2010
  • 23,033
  • 6
  • 64
  • 66