C# 调用powershell脚本并通过C将输出捕获到ASP#
我正在ASP页面中从c#调用PowerShell脚本。脚本执行得很好,但是我的PowerShell的输出(C# 调用powershell脚本并通过C将输出捕获到ASP#,c#,asp.net,powershell,C#,Asp.net,Powershell,我正在ASP页面中从c#调用PowerShell脚本。脚本执行得很好,但是我的PowerShell的输出(write host)没有被捕获。我想能够捕获任何输出回到ASP页面 以下是我当前的代码 protected void ExecuteInputClick(object sender, EventArgs e) { Result.Text = string.Empty; RunspaceConfiguration ru
write host
)没有被捕获。我想能够捕获任何输出回到ASP页面
以下是我当前的代码
protected void ExecuteInputClick(object sender, EventArgs e)
{
Result.Text = string.Empty;
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
string scriptfile = "C:\\PRJ_Templates\\CreateProject.ps1";
Command myCommand = new Command(scriptfile);
CommandParameter DestDirParam = new CommandParameter("DestinationDirectory", DropDownList1.SelectedValue);
CommandParameter ProjNamParam = new CommandParameter("ProjectName", Input.Text);
myCommand.Parameters.Add(DestDirParam);
myCommand.Parameters.Add(ProjNamParam);
pipeline.Commands.Add(myCommand);
try
{
System.Collections.ObjectModel.Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
Result.Text = Server.HtmlEncode(stringBuilder.ToString());
}
catch (ActionPreferenceStopException Error) { Result.Text = Error.Message; }
catch (RuntimeException Error) { Result.Text = Error.Message; }
}
protectedvoid ExecuteInputClick(对象发送方,事件参数e)
{
Result.Text=string.Empty;
RunspaceConfiguration RunspaceConfiguration=RunspaceConfiguration.Create();
Runspace Runspace=RunspaceFactory.CreateRunspace(runspaceConfiguration);
Open();
RunspaceInvoke scriptInvoker=新的RunspaceInvoke(运行空间);
Pipeline Pipeline=runspace.CreatePipeline();
string scriptfile=“C:\\PRJ\u Templates\\CreateProject.ps1”;
命令myCommand=新命令(脚本文件);
CommandParameter DestDirParam=新的CommandParameter(“DestinationDirectory”,DropDownList1.SelectedValue);
CommandParameter ProjNamParam=新的CommandParameter(“ProjectName”,Input.Text);
myCommand.Parameters.Add(DestDirParam);
myCommand.Parameters.Add(ProjNamParam);
pipeline.Commands.Add(myCommand);
尝试
{
System.Collections.ObjectModel.Collection results=pipeline.Invoke();
runspace.Close();
StringBuilder StringBuilder=新的StringBuilder();
foreach(结果中的PSObject对象)
{
stringBuilder.AppendLine(obj.ToString());
}
Result.Text=Server.HtmlEncode(stringBuilder.ToString());
}
catch(ActionPreferenceStopException错误){Result.Text=Error.Message;}
catch(运行时异常错误){Result.Text=Error.Message;}
}
有没有想过为什么写入主机没有被放入结果中?.Invoke()
只捕获成功输出流中的内容(通过写入输出
,或者更典型地,通过隐式输出)。相比之下,任何其他流都必须通过.streams
属性访问,包括写入主机
写入的信息流。更广泛地说:,除非目的是只写入显示器,绕过成功输出流,并能够将输出发送到其他命令,将其捕获到变量中,将其重定向到一个文件。要输出值,请单独使用它;e、 例如,$value
而不是写主机$value
(或者使用写输出$value
,尽管这很少需要)。另请参见:的底部部分