Tom*_*Tom 2 c# powershell runspace
在 Powershell 中运行脚本时,我能够接收 Write-Host 输出,但在 C# 中则无法接收。
以下是输出 Write-Host“HELLO WORLD TEST”的代码。
当应用程序到达此行时失败:
Collection<PSObject> results = pipeline.Invoke()
;
我收到此错误消息:
HostException:由于宿主程序或命令类型不支持用户交互而提示用户失败的命令。尝试使用支持用户交互的主机程序(例如 Windows PowerShell 控制台或 Windows PowerShell ISE),并从不支持用户交互的命令类型(例如 Windows PowerShell 工作流)中删除与提示相关的命令
如何返回 Write-Host 的输出?提前致谢。
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
RunScript(@"C:\TestScript.ps1");
}
}
private string RunScript(string scriptText) {
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection < PSObject > results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach(PSObject obj in results) {
//do something
}
return Textbox.Text;
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用 PowerShell。创建一个实例并为您感兴趣的所有 Powershell 流添加侦听器:
private string RunScript(string scriptText)
{
System.Management.Automation.PowerShell powerShellInstance = System.Management.Automation.PowerShell.Create();
powerShellInstance.Streams.Information.DataAdded += InformationHandler;
powerShellInstance.Streams.Verbose.DataAdded += InformationalRecordEventHandler<VerboseRecord>;
powerShellInstance.Streams.Debug.DataAdded += InformationalRecordEventHandler<DebugRecord>;
powerShellInstance.Streams.Warning.DataAdded += InformationalRecordEventHandler<WarningRecord>;
powerShellInstance.AddScript(scriptText);
powerShellInstance.Invoke();
}
static void InformationalRecordEventHandler<T>(object sender, DataAddedEventArgs e)
where T : InformationalRecord
{
var newRecord = ((PSDataCollection<T>)sender)[e.Index];
if (!string.IsNullOrEmpty(newRecord.Message))
{
//STORE your message somewhere
}
}
static void InformationHandler(object sender, DataAddedEventArgs e)
{
var newRecord = ((PSDataCollection<InformationRecord>)sender)[e.Index];
if (newRecord?.MessageData != null)
{
//STORE your message somewhere
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4103 次 |
最近记录: |