简体   繁体   English

从其他Powershell同步运行PowerShell脚本

[英]Running powershell script from other powershell synchronically

I have 2 powershell scripts (A.ps1 and B.ps1). 我有2个powershell脚本(A.ps1和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 (ie running B.ps1 in an async way). 我想从脚本A.ps1调用脚本B.ps1,但是让A.ps1在调用B.ps1之后继续执行,而不是等待B.ps1完成执行(即以异步方式运行B.ps1) )。

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. 但这会导致脚本A等待脚本B完成。

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) 但是由于某种原因,此cmdlet根本无法在我的计算机上运行(它实际上打开了“您想如何打开此文件?”窗口,无论我选择什么,都继续显示此窗口)

I'm using powershell version 5.1 我正在使用Powershell 5.1版

Thanks, 谢谢,

Noam 诺姆

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. 我已经设置了睡眠计时器,以向您显示即使B.ps1启动记事本并等待5秒钟, A.ps1仍然继续显示第二个计时器,并且不等待B.ps1完成。

A.ps1 : (displays a timer second by second until 10) A.ps1 :(每秒显示计时器直到10)

1..10 | ForEach-Object {
    Start-Sleep -Seconds 1
    Write-Host $_
    if($_ -eq 3){
        Start-Job -FilePath .\B.ps1
    }
}

B.ps1 : (starts a notepad) B.ps1 :(启动记事本)

Start-Process notepad
Start-Sleep -Seconds 5

Refer to Example 4 in this link . 请参阅此链接中的示例4。

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. 您可以在Get-Help about_JobsGet-Help about_Job_Details和各个命令的Get-Help条目中了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM