0

I was assuming that it is possible to start a process in PowerShell using Start-Job without having to wait for its completion. But apparently is not the case when I'm starting PowerShell from cmd.exe because I have to use the Wait-Job cmdlet.

So I have two files:

my-hook-runner.cmd

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\mydir\my-hook-ps.ps1

my-hook-ps.ps1

Start-Job -ScriptBlock { gci C:\mydir | Out-File C:\mydir\test.txt } 

The script my-hook-ps.ps1 creates a job and it adds the test.txt file when I run it from PowerShell console. But when I run my-hook-runner.cmd or powershell.exe C:\mydir\my-hook-ps.ps1 in cmd.exe, the file text.txt is not added although the job is created.

It works when I pipe Start-Job into Wait-Job but this negates all the benefits of using these jobs because I have to wait for their completion.

Since the ps1 file is not executable on Windows, I have to start it from cmd.exe, and I want to spawn a detached process that lives on its own (because of this Running another program in Windows bat file and not create child process).

The behavior is similar or identical to the one described at https://social.technet.microsoft.com/Forums/ie/en-US/a2c4741d-8c6b-4277-afcd-bbdc73ca8deb/startjob-works-from-powershell-but-not-from-cmd?forum=winserverpowershell.

I'd appreciate any comments, suggestions and also answers to the following questions:

  • Why the PowerShell job works when I run it from PowerShell but does not work when I run it from cmd.exe? Is this about closing the job's PSSession when it hasn't yet finished running?

  • Is it possible to start PowerShell jobs from cmd.exe without waiting for their completion?

bahrep
  • 29,961
  • 12
  • 103
  • 150
  • It seems that I've solved my original problem with `powershell – bahrep Dec 22 '22 at 11:50
  • When a parent process terminates all children processes will also terminate unless the children are run asynchronously. So when your powershell terminates (parent) any spawn children will also terminate. – jdweng Dec 22 '22 at 14:16
  • @jdweng even jobs terminate? I was assuming that the idea of a background job and ‘Start-Job’ is create independently running processes. – bahrep Dec 22 '22 at 14:34
  • Where are you starting a "BACKGROUND PROCESS"? When I said Asynchronously it is same as background job. You are not starting a background job so when Powershell terminates so does the children. – jdweng Dec 22 '22 at 16:47

0 Answers0