简体   繁体   English

如何等待脚本完成?

[英]How do I wait for script to finish?

I have three scripts which is invoked by the function below.我有三个脚本,由下面的函数调用。 while the first script is still running the subsequent commands get called which stops my first command from finishing.当第一个脚本仍在运行时,会调用后续命令,这会阻止我的第一个命令完成。

public static void InvokePowerShellCommand(this string command)
{
   var powerShell = PowerShell.Create();
   powerShell.AddScript(command).Invoke();            
}

I would like to ensure that the script finishes before proceeding to the next one, how can I achieve this?我想确保脚本在继续下一个之前完成,我怎样才能做到这一点?

Add an event handler to the call, a really simple example would be向调用添加一个事件处理程序,一个非常简单的例子是

    private static PSInvocationState state;
    public static void InvokePowerShellCommand(this string command)
    {
        state = PSInvocationState.NotStarted;
        PowerShell ps = PowerShell.Create();
        ps.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(InvocationStateChanged);
        ps.AddScript(command);
        ps.Invoke();
        while (state == PSInvocationState.Running)
            System.Threading.Thread.Sleep(100);

    }

    static void InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e)
    {
        state = e.InvocationStateInfo.State;
    }

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

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