0

I have a powershell script, that starts x number of Jobs. If I start it from powershell, the processes stays alive, but if start from cmd, after the script finishes every process stops.

The only way I can keep the processes alive, is to put Sleep in the script. Why is that?

This is how I start the script from cmd: Powershell.exe .\scripts\cpu_load.ps1 -UtilizeCorePercent 50

  • Because the main process is ready and the rest of your Jobs run in a different threat. You need to [`Wait-Job`](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/wait-job) and/or `Receive-Job`. – iRon Nov 15 '22 at 14:50

1 Answers1

1

The PowerShell.exe has 2 main modes of operations.

  1. A terminal mode where you can run multiple scripts or individual commands.
  2. An execution mode where PowerShell.exe starts running, it then executes a script that was passed to it as a parameter, continues to run until the script exits, and then the PowerShell.exe exits or closes.

In terminal mode, variables you assign, jobs you start, and more, will stay active and available until you exit the PowerShell.exe terminal. Similarly, in execution mode, everything remains available until the script exits - which exits the PowerShell.exe.

The CMD terminal allows you to execute exe programs such as Notepad.exe and PowerShell.exe, but you have to understand that CMD.EXE is, itself, an executable program ran typically by a shortcut placed somewhere in your Windows Desktop.

The fact that CMD is its own exe program means that it has no "awareness" of any type of other exe programs, and, as such, it will not preserve anything from those other exe programs after they close.

The only solutions is something similar to iRon's comment on using "Wait-Job and/or Receive-Job", where, in some fashion, PowerShell.exe remains running until the job(s) are done.

Darin
  • 1,423
  • 1
  • 10
  • 12
  • Thank, both of you, very much the answear – MMartin2000 Nov 15 '22 at 18:11
  • @MMartin2000, you are welcome. Also, keep learning PowerShell, Windows, other operating systems, etc... What I'm finding is that It's harder to learn anything at first, but the deeper I go the easier it is to learn. I'm thinking this is universally true of everyone. The more you know, the more you are able to know. – Darin Nov 15 '22 at 19:22