Resolving Variables within Scriptblocks for Jobs

Viewed 28

I have a job setup to run/call a script that outputs a file. The code works fine when run on it's own. I have verified the job is not being blocked and completes successfully. However, no file is generated when the script is called from the job. I'm even doing something very similar elsewhere without an issue, in fact it is from another similar set up that I pulled this code to begin with. Anyway, here is what I have:

When run as job, no file output:

$McShieldCheckerJob = Start-Job -ScriptBlock { 
    E:\ICSScoreCardUtilityPack\ServiceAndProcessCheckerV1.0.ps1 -ServicesAndOrProcesses 'McShield' -Comps 'COMP15' `
    -OutputMode 1 -OutputFile $McShieldCheckOutputFileName  -GroupByMachine "N" -AsJob "Y"
} -Name McShieldCheckerJob

When run not as a job, file outputs as expected.

E:\ICSScoreCardUtilityPack\ServiceAndProcessCheckerV1.0.ps1 -ServicesAndOrProcesses 'McShield' -Comps 'COMP15' `
    -OutputMode 1 -OutputFile $McShieldCheckOutputFileName  -GroupByMachine "N" -AsJob "Y"

Stumped as to why this won't work exactly the same as a job vs. not as a job. Again, I have verified via Get-Job and Receive-job that the job is not being blocked and is completing successfully.

enter image description here

EDIT: It seems the variable $McShieldCheckOutputFileName cannot be resolved within the scriptblock for the job. If I use a string literal [for $McShieldCheckOutputFileName] I do not have the issue. (I was able to determine after a bit more troubleshooting that the lack of an output file when running as a job was due to a null value for my output file name.) So, I can probably work around this easily enough, but still this seems curious that a variable cannot be resolved within the scriptblock? Must be a scope thing...

1 Answers

Figured it out... here is how it is done:

$McShieldCheckerJob = Start-Job -ScriptBlock { 
    E:\ICSScoreCardUtilityPack\ServiceAndProcessCheckerV1.0.ps1 -ServicesAndOrProcesses 'McShield' -Comps 'PCNWK15' `
    -OutputMode 1 -OutputFile "$($args[0])" -GroupByMachine "N"
} -Name McShieldCheckerJob -ArgumentList $McShieldCheckOutputFileName

As we can see, we need to specify an -Argumentlist to the script block, then reference said arguments within the scriptblock via the $args variable.

Reference (see example 10)

Related