How to pass values to nested ForEach?

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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;             }         } }

回答1:

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


回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!