Reputation: 1804
I have 2 powershell scripts (A.ps1 and B.ps1).
I want to call script B.ps1 from script A.ps1, but let A.ps1 continue with it execution after calling B.ps1 and not to wait for B.ps1 to finish its execution (i.e. running B.ps1 in an async way).
How can that be achieved? I tried:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\scripts\B.ps1'"
but that causes script A to wait until script B is done.
I also tried:
Start-Process 'C:\scripts\B.ps1'
But for some reason this cmdlet doesn't work on my machine at all (it actually opens up the "How do you want to open this file?" window and no matter what I choose it just keep showing this window)
I'm using powershell version 5.1
Thanks,
Noam
Upvotes: 0
Views: 119
Reputation: 32145
At the beginning of your Script:
$Job = Start-Job -FilePath 'C:\Path\To\Script.ps1';
#Script continues here
Then, if the script has output, at end of script:
$Output = Wait-Job $Job | Receive-Job;
Remove-Job $Job;
# Do whatever with $Output
If the script didn't have output:
Wait-Job $Job | Remove-Job;
Obviously, there's no error checking or correction here at all. Jobs can be in a failed state or return errors, and ideally you'll want to handle that. You can learn more at Get-Help about_Jobs
, Get-Help about_Job_Details
, and the Get-Help
entries for the individual commands.
Upvotes: 0
Reputation: 1742
These are scripts examples :
I have set sleep timers to show you that even if B.ps1 starts notepad and wait 5 seconds after, A.ps1 still continues to display second by second timer and does not wait for B.ps1 to be finished.
A.ps1 : (displays a timer second by second until 10)
1..10 | ForEach-Object {
Start-Sleep -Seconds 1
Write-Host $_
if($_ -eq 3){
Start-Job -FilePath .\B.ps1
}
}
B.ps1 : (starts a notepad)
Start-Process notepad
Start-Sleep -Seconds 5
Refer to Example 4 in this link.
Upvotes: 1