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;
}
}
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With