2

Suppose I have a simple Job that starts off like this:

$job = Start-Job -ArgumentList 1, 2 -ScriptBlock {
        $var1 = $args[0]
        $var2 = $args[1]

        $var3 = $var1 + $var2

        Write-Host $var3
}

Now suppose that I want to continue executing the session that is $job and introduce new arguments and simply continue executing inside $job.

From what I understand, that's not how Jobs work in Powershell. Once the commands inside the job were executed, the job is considered to be completed and can no longer be recycled. If my understanding is correct, is there any other way to achieve the effect of effectively having a background task inside your powershell session that you can continue injecting with new commands/variables, without having to create a new job/session/process? For clarity, this is local (on the same machine).

RecursiveCall
  • 482
  • 3
  • 13

2 Answers2

2

I think you would be better of looking into PowerShell runspaces instead that can communicate back and forth with each other since they are threads of the same processes.

Start-Job actually starts a new PowerShell session in a separate isolated process.

See, MS Docs - Start-Job -RunAs32 and MS Scripting - Beginning Use of PowerShell Runspaces

Dennis
  • 871
  • 9
  • 29
2

Dennis' helpful answer provides the crucial pointer: use the PowerShell SDK to create an in-process PowerShell instance that you can use for repeated invocation of commands.

The following sample code demonstrates this: It keeps prompting you for a command to execute and uses a single, reusable PowerShell instance to execute it (press Ctrl-C to exit):

$ps = [powershell]::Create()

while ($true) {
  $cmd = Read-Host 'Type a command to execute'
  # Execute and output the results.
  $ps.AddScript($cmd).Invoke()
  # Relay errors, if any.
  $ps.Streams.Error | Write-Error
  # Reset in preparation for the next command.
  $ps.Commands.Clear(); $ps.Streams.ClearStreams()
}
mklement0
  • 382,024
  • 64
  • 607
  • 775