Search code examples
sessionloggingpowershellparameter-passingremoting

Passing variable to several scriptblocks used in remote sessions Powershell


I have a script that runs from a domain server and 'does work' on a domain server.

The work is divided up into jobs that are in scriptblocks that are called with invoke-command using a stored PSsession.

Results are logged on the domain server in a log file that includes a datetime stamp in the logfile name.

Now, I need to add another log that needs to reside on the remote on which the work is done. The log name format also needs to include a date and time stamp.

My problem is passing the name of the log to each of the jobs so that they write to the same file. I've played around with -ArgumentList, @args, and $args which I can get to run without errors but do nothing so I am not passing the logfile name correctly.

Below is a super simplified version of how I've structured my script.

Is it a mistake to nest the Start-Job in another script block? How would I pass my unique log file name to a number of these scriptblocks to capture success/failure and specific points?


#log file names, ps session and other variables declared here  

  $DoDomainWorkScriptBlock = {

    Try {

            start-job -name DoDomainWorkjob -scriptblock{

          $command = "C:\Program Files\someprogram\someprogram.exe"

          & $command  -f someargs


            If ($? -ne "True") {Throw 'Do work failed’}

            " Do non-domain work job completed. "

            }

        } Catch {$Error[0] | Out-File $ErrorLog -Append}

    }

#other jobs nested in other scriptblocks like the one above here

Invoke-Command -session $RemoteSession -scriptblock $DoDomainWorkScriptblock | Out-File $DomainProgressLog -Append

Invoke-Command -session $RemoteSession -command{Wait-Job -name DoDomainWorkjob } | Out-File $DomainProgressLog -Append

Invoke-Command -session $RemoteSession -command{Receive-Job -Name DoDomainWorkjob } | Out-File $DomainProgressLog –Append


#invoke start, wait, and receive job commands for the other jobs

Solution

  • You can pass arguments to script blocks like this:

    $code = {
      param( $foo )
      Write-Host $foo
    }
    
    $bar = "bar"
    Invoke-Command -ScriptBlock $code -ArgumentList $bar