如何从powerhell脚本块获取返回值在c#中启动

时间:2016-09-01 12:55:14

标签: c# powershell

我尝试从使用c#中的新进程开始的powershell scriptblock获取返回值。

    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();
}

E.g。 scriptblock" isEnabledBase64String"返回一个数字。 我怎么得到这个号码?有什么建议? 感谢

1 个答案:

答案 0 :(得分:0)

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

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

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