Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a separate PowerShell script asynchronously while continuing the current script

Tags:

powershell

PowerShell script #1 does the following:

Performs FTP ops ending with saving updated remote directory data in a local file

The script runs quickly until the remote directory data must be obtained using FTP. It would be desirable to remove the remote directory data retrieval into a different PowerShell script #2.

This SO post explains launching a script from within a script. But it seems in this case the first script is suspended while the second script executes.

How can I code script #1 so that script #2 is launched and forgotten and script #1 continues and completes quickly leaving script #2 to finish in the background.

like image 348
Alan Avatar asked May 02 '26 23:05

Alan


1 Answers

You can use Start-Job to starts a PowerShell background job. This way the job runs without interacting with the current session and will return immediately while the job is running asynchronously. If you expect receiving a result from the job, you can use Receive-Job to get the result.

Example

  • Start-Job -ScriptBlock {Get-Process}
  • Start-Job -Command "Get-Process"
  • Start-Job -FilePath "D:\script.ps1"

You can also use Start-Process to start another process. You can specify a program executable file or script file, or a file that can be opened by using a program on the computer. When you start process for a non-executable file, the program associated to that file type will run like when you use Invoke-Item cmdlet.

Example

  • Start-Process PowerShell -Argument "C:\MyScript.ps1"
  • Start-Process "C:\SomeFile.txt"
like image 122
Reza Aghaei Avatar answered May 07 '26 09:05

Reza Aghaei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!