【问题标题】:How to get the return value from a powershell scriptblock started in c#如何从 c# 中启动的 powershell 脚本块获取返回值
【发布时间】:2017-01-09 08:59:02
【问题描述】:

我尝试从以 c# 中的新进程开始的 powershell 脚本块获取返回值。

    Process powershellProcess = null;
try
{
    powershellProcess = new Process();
    powershellProcess.StartInfo.FileName = "powershell.exe";
    powershellProcess.StartInfo.Arguments = string.Format("-EncodedCommand {0}", isEnabledBase64String);
    powershellProcess.StartInfo.RedirectStandardInput = false;
    powershellProcess.StartInfo.RedirectStandardError = false;
    powershellProcess.StartInfo.RedirectStandardOutput = false;
    powershellProcess.StartInfo.UseShellExecute = false;
    powershellProcess.StartInfo.CreateNoWindow = true;
    bool value = powershellProcess.Start();
    powershellProcess.BeginOutputReadLine();
    while (!powershellProcess.HasExited)
    {
        Thread.Sleep(1000);
    }
    powershellProcess.CancelOutputRead();
}
catch (Exception ex)
{
    throw ex;
}
finally
{
    powershellProcess.Close();
}

例如脚本块“isEnabledBase64String”返回一个数字。 我怎样才能拿到号码?有什么建议吗? 谢谢

【问题讨论】:

  • 解决方法:如果使用了 powershellProcess.OutputDataReceived += OnOutputDataReceived,则可以只使用 Write-Host xxx 并在 OnOutputDataReceived 中获取它。缺点:它是一个黑客。

标签: c# powershell


【解决方案1】:

是否必须启动一个进程才能执行 powershell 脚本?您可以使用 System.Management.Automation 中的 powershell 实例对象。

参见 c# 的 windows powershell 示例 https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

这将使您能够更好地控制脚本的执行、传递参数以及读取输出。

【讨论】:

  • 是的。因为之后我重定向 powershellProcess.StartInfo.RedirectStandardOutput = true; powershellProcess.OutputDataReceived += OnOutputDataReceived;并捕获收到的输出数据
猜你喜欢
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多