【问题标题】:Powershell Process from C# doesn't completeC# 中的 Powershell 进程未完成
【发布时间】:2015-11-03 21:43:20
【问题描述】:

我正在尝试从 C# 运行 PS 脚本,并将 Powershell 作为进程,如下所示:

 ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName =   configFile.AppSettings.Settings["PSDir"].Value.ToString() + @"\powershell.exe";
        startInfo.Arguments = @"& '" + scriptPath + "'\"";
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardError = true;
        startInfo.UseShellExecute = false;
        startInfo.CreateNoWindow = true;

        Process process = new Process();
        process.StartInfo = startInfo;            
        process.Start();

        return process;

我这样称呼那个方法:

        Process proc = RunPSScript(startupPath + "\\stats.ps1");
        proc.WaitForExit();

程序卡在:

proc.WaitForExit();

我可以说脚本的初始部分已经完成,但除此之外什么都没有。不是脚本不好,因为我已经在代码之外运行它并且运行得非常好。

当我删除 WaitForExit() 时,进程调用立即存在并且程序继续运行,但这并不好,因为我需要让脚本生成数据,然后程序的其余部分才能继续运行。

奇怪的是,如果我在启动 PS 调用后结束调试会话,脚本会继续运行,并且锁定其完成的任何东西现在都消失了,它会继续运行直到完成。

任何想法表示赞赏。

谢谢!

【问题讨论】:

  • 您可能需要在进程退出之前读取进程的输出流。
  • 添加到 Mark W 的评论:stackoverflow.com/questions/26713373/…
  • 对链接进行了升级...绝对是骗子。
  • AARrrgghh,问题出在这一行: startInfo.Arguments = @"& '" + scriptPath + "'\""; 需要删除 \" ,现在可以了。傻我!

标签: c# powershell process


【解决方案1】:

要检查的两件事,你的论点的确切输出是什么?鉴于以管理员身份从 CMD 提示符运行相同的脚本,看看它是否具有相同的结果。您还可以将超时传递给以毫秒为单位的等待退出。试试这个:

RunPSScript(startupPath + "\\stats.ps1").WaitForExit();

【讨论】:

  • 见我上面的评论,我的论点有一个坏字符。不过谢谢!
猜你喜欢
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
相关资源
最近更新 更多