Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass values to nested ForEach?

Tags:

powershell

I am trying to use a variable created in an outer ForEach loop inside an inner ForEach loop. The value does not pass thru as I expect and is always null.

Notice The value for $server is always null can you tell me why and how to fix?

$Srvrs = "SVR1";
$Srvrs | ForEach-Object {


    $server = $_;
    Write-Host "Server value in outer Foreach:" $server;

    $sourceFilesLoc = "D:\Test\SetupSoftwareAndFiles"
    $sourceFiles = Get-ChildItem -LiteralPath $sourceFilesLoc;

    $sourceFiles | ForEach-Object  {
        Start-Job -InputObject $server -ScriptBlock     {
            Write-Host "Server value in inner Foreach:" $server;
            }
        }
}
like image 848
ChiliYago Avatar asked Dec 22 '22 16:12

ChiliYago


2 Answers

Pass in the parameters via the -ArgumentList parameter e.g.:

Start-Job -InputObject $server -ScriptBlock {param($svr)
    Write-Host "Server value in inner Foreach:" $svr;
} -ArgumentList $server

Here's a simple example of using -ArgumentList:

PS> $server = 'acme'
PS> $job = Start-Job {param($svr) "server is $svr"} -ArgumentList $server
PS> Receive-Job $job
server is acme
like image 129
Keith Hill Avatar answered Jan 11 '23 13:01

Keith Hill


the issue isn't accessing the variable in nested foreaches.. if you did a write-host of the variable inside the inner foreach it would be fine. Its a matter of passing the variable to the job. Jobs are different processes that run in the background.

like image 40
klumsy Avatar answered Jan 11 '23 13:01

klumsy