Question:
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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
$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; } } } |
Answer:
Pass in the parameters via the -ArgumentList
parameter e.g.:
1 2 3 4 |
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
:
1 2 3 4 5 |
PS> $server = 'acme' PS> $job = Start-Job {param($svr) "server is $svr"} -ArgumentList $server PS> Receive-Job $job server is acme |