Alan
Alan

Reputation: 1637

Run a separate PowerShell script asynchronously while continuing the current script

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.

Upvotes: 2

Views: 15447

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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"

Upvotes: 12

Boreaz
Boreaz

Reputation: 32

You would have a single script with multiple functions. The script is a standard ps1 script. The use-case here is you are executing blocks of code that do effectively a single task and you get to decide which blocks to execute at which stage of the script execution:

Function Get-RemoteDirectory {

   <Insert shorter running operation here>

}

Function Pull-RemoteDirectory {

  Get-RemoteDirectory -Path <Path>

  <Insert longer running operation here>

}

Pull-RemoteDirectory -SourcePath <Path> -DestinationPath <Path>

Here I am calling the first function within the second function. You can insert your script logic as you like here. Be careful about variable scopes. Once your script is ready just save the file and execute as any Powershell script.

NB. You can add param() blocks to your script and/or to your functions. Whatever suits your needs depending on script runtime requirements.

Upvotes: -2

Related Questions