我有类似但不同的问题,例如How to redirect Powershell output from a script run by TaskScheduler and override default width of 80 characters。
我有很久以前编写的自定义安装程序框架。在其中我可以执行“任务”。我最近不得不添加一个任务来执行PowerShell脚本。现在,即使任务是用C#编写的,我也无法直接调用PowerShell脚本中的命令。不幸的是,这已不在考虑范围之内。
简而言之,我想从C#调用PowerShell可执行文件并将其输出重定向回我的应用程序。这是我到目前为止所做的:
我可以使用以下代码(来自我创建的测试项目)成功调用PowerShell:
string powerShellExeLocation = null;
RegistryKey localKey = Registry.LocalMachine;
RegistryKey subKey = localKey.OpenSubKey(@"SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine");
powerShellExeLocation = subKey.GetValue("ApplicationBase").ToString();
if (!Directory.Exists(powerShellExeLocation))
throw new Exception("Cannot locate the PowerShell dir.");
powerShellExeLocation = Path.Combine(powerShellExeLocation, "powershell.exe");
if (!File.Exists(powerShellExeLocation))
throw new Exception("Cannot locate the PowerShell executable.");
string scriptLocation = Path.Combine(Environment.CurrentDirectory, "PowerShellScript.ps1");
if (!File.Exists(scriptLocation))
throw new Exception("Cannot locate the PowerShell script.");
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = Environment.CurrentDirectory;
processInfo.FileName = powerShellExeLocation;
processInfo.Arguments = "-NoLogo -OutputFormat Text -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + scriptLocation + "\" ";
Process powerShellProcess = new Process();
powerShellProcess.StartInfo = processInfo;
powerShellProcess.OutputDataReceived += new DataReceivedEventHandler(powerShellProcess_OutputDataReceived);
powerShellProcess.ErrorDataReceived += new DataReceivedEventHandler(powerShellProcess_ErrorDataReceived);
powerShellProcess.Start();
while (!powerShellProcess.HasExited)
{
Thread.Sleep(500);
}
永远不会调用重定向输出的处理程序:
void powerShellProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
和
void powerShellProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
我相信脚本正在运行。现在我只有一个输出PATH内容的测试脚本。
$a = $env:path; $a.Split(";")
我在PowerShell实例中对此进行了测试,并且输出正确。
如何让PowerShell输出重定向到我的C#代码?我不想依赖我将执行的脚本来处理自己的日志记录。我宁愿收集他们的输出并在框架的日志记录机制中处理它。
修改 意识到我离开了奇怪的循环,等待该代码示例中的退出。我有一个过程“WaitForExit”:
powerShellProcess.WaitForExit();
修改
使用@MiniBill的建议。我提出了以下代码snippit:
powerShellProcess.Start();
while (!powerShellProcess.HasExited)
{
string line;
while (!string.IsNullOrEmpty((line = powerShellProcess.StandardOutput.ReadLine())))
this.LogInfo("PowerShell running: " + line);
}
这可以很好地处理输出。它正在削减我80行的字符:(但我可以忍受,除非其他人可以提出修复建议!
更新解决方案
/*
* The next few lines define the process start info for the PowerShell executable.
*/
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.WorkingDirectory = Environment.CurrentDirectory;
//this FileName was retrieved earlier by looking in the registry for key "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" and the value for "ApplicationBase"
processInfo.FileName = powerShellExeLocation;
//if we're going to use script arguments build up the arguments from the process start correctly.
if (!string.IsNullOrEmpty(this.ScriptArguments))
processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\" '" + ScriptArguments + "'";
else
processInfo.Arguments = "-NoLogo -NonInteractive -WindowStyle Hidden -ExecutionPolicy Unrestricted -File \"" + ScriptLocation + "\"";
//create the Process object, set the start info, and start the process
Process powerShellProcess = new Process();
powerShellProcess.StartInfo = processInfo;
powerShellProcess.Start();
/*
* While the PowerShell process hasn't exited do the following:
*
* Read from the current position of the StandardOutput to the end by each line and
* update the tasks progress with this information
*
* Read from the current position of StandardError to the end by each line, update
* the task's progress with this information and set that we have an error.
*
* Sleep for 250 milliseconds (1/4 of a sec)
*/
bool isError = false;
while (!powerShellProcess.HasExited)
{
string standardOuputLine, standardErrorLine;
while (!string.IsNullOrEmpty((standardOuputLine = powerShellProcess.StandardOutput.ReadLine())))
{
this.UpdateTaskProgress(standardOuputLine);
}
while (!string.IsNullOrEmpty((standardErrorLine = powerShellProcess.StandardError.ReadLine())))
{
this.UpdateTaskProgress(standardErrorLine);
isError = true;
}
Thread.Sleep(250);
}
/*
* Now that the process has completed read to the end of StandardOutput and StandardError.
* Update the task progress with this information.
*/
string finalStdOuputLine = powerShellProcess.StandardOutput.ReadToEnd();
string finalStdErrorLine = powerShellProcess.StandardError.ReadToEnd();
if (!string.IsNullOrEmpty(finalStdOuputLine))
this.UpdateTaskProgress(finalStdOuputLine);
if (!string.IsNullOrEmpty(finalStdErrorLine))
{
this.UpdateTaskProgress(finalStdErrorLine);
isError = true;
}
// there was an error during the run of PowerShell that was output to StandardError. This doesn't necessarily mean that
// the script error'd but there was a problem. Throw an exception for this.
if (isError)
throw new Exception(string.Format(CultureInfo.InvariantCulture, "Error during the execution of {0}.", this.ScriptLocation));
答案 0 :(得分:4)
您想使用Process.StandardOutput
属性。这是一个可以打开以获取程序输出的流