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
CodePudding user response:
The PowerShell.exe has 2 main modes of operations.
- A terminal mode where you can run multiple scripts or individual commands.
- 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.