sniper2100
sniper2100

Reputation: 13

Pass variable to subscript

I have a simple script in PowerShell with a list and a Job

$file_bme1 = "C:\file1.txt"
$file_bme2 = "C:\file2.txt"
$scriptList =@(
    'C:\Program Files\PuTTY\collection1.ps1'
    'C:\Program Files\PuTTY\collection2.ps1'
);
sleep -seconds 10
Write-Output "Script starting..."
foreach ($i in 1..1){
Write-Output "Loop $i"
$jobs=foreach($script in $scriptList){
    Start-Job -ScriptBlock {& $using:script}
    }
$jobs | Wait-Job | Receive-Job 2>$null
Write-Output "End of Loop $i"
sleep -seconds 30
}
Write-Output "Script completed."

I would like to pass variable $file_bme1 and $file_bme2 to the subscripts (collection1.ps1 and collection2.ps1), but I'm having issues on how to achieve that. Any recommendation?

Upvotes: 1

Views: 415

Answers (1)

mklement0
mklement0

Reputation: 437090

It sounds like you want to enumerate two arrays (collections) in tandem, i.e. to process the first element from one collection together with the first element from another, and so on.

There is (unfortunately) no direct way to do that, but you can use indexing:

# Create a second list that parallels $scriptList
$fileList = $file_bme1, $file_bme2

# Loop over the list (array) indices and pass the corresponding
# elements from the two lists to Start-Job
$jobs = foreach ($i in 0..($scriptList.Count-1)) {
  # Invoke script $scriptList[$i] with $fileList[$i] as its argument.
  Start-Job -ScriptBlock { & $args[0] $args[1] } -Args $scriptList[$i], $fileList[$i]
}

Upvotes: 1

Related Questions