Trouble backgrounding .bat file invocations

rated by 0 users
This post has 2 Replies | 1 Follower

Not Ranked
Posts 1
BillJr58 Posted: 04-13-2012 10:40 PM

Background:
I'm using PowerShell to automate a legacy build process.  There are a couple .bat files I need to invoke and would like to run them in parallel.  They end with a "Pause" command, so I need to supply input in order for the jobs to complete.

I can invoke the .bat files serially, simply using " " | to satisfy the Pause command.  The trouble began when I tried to use Start-Job to run them in parallel.  Can you explain why PowerShell is not happy with this code?

Code snippet:

   $jobs = @()
   foreach ( $jn in "compile_all_ada", "compile_all_c" ) {
      $bf = (Get-Location),"$jn.bat" -join "\"
      $jobs += Start-Job {
         (" " | & $bf) | Out-File -FilePath $jn.log -Encoding ascii -Force
         } -Name $jn
   }

Invocation error:

>>> $jobs | Receive-Job
The expression after '&' in a pipeline element produced an invalid object. It must result in a command name, script block
or CommandInfo object.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadExpression

Top 10 Contributor
Posts 637
Microsoft MVP
Top Contributor

Do not use Start-Job.

Do use Start-Process.

Top 10 Contributor
Posts 637
Microsoft MVP
Top Contributor

And regarding your question: whenever you hand over a script block to someone else (like Start-Job), variables will only survive if the script block runs in the same context. With Start-Job, you are initiating a completely new powershell.exe session with its own set of variables. So they are all empty.

Page 1 of 1 (3 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.