繁体   English   中英

如何从C#中启动的Powershell脚本块获取返回值

[英]How to get the return value from a powershell scriptblock started in c#

我尝试从以C#中的新Process开始的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”返回一个数字。 我如何获得电话号码? 有什么建议吗? 谢谢

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

请参阅Windows Powershell上的示例(来自C# https: //blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

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

暂无
暂无

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

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