我有一段代码,使用c#来执行powercli命令行。但是在使用过程中有的powershell命令很耗费时间,因此需要把执行命令的代码放在后台执行,然后返回结果。
我打算使用workbackgroundworker修改代码,把执行powercli命令行的部分放在DoWork里面去跑,然后通过ProgressChanged来显示运行的结果。但是我修改代码后不显示任何信息。在此向各位求助,望各位不吝赐教,帮我看看问题在哪里。
代码如下:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace RunPowerShell
{
public partial class FormPowerShellSample : Form
{
// Represents the kind of drag drop formats we want to receive
private const string dragDropFormat = "FileDrop";
public FormPowerShellSample()
{
InitializeComponent();
}
private void buttonRunScript_Click(object sender, EventArgs e)
{
try
{
textBoxOutput.Clear();
Worker.RunWorkerAsync(textBoxScript.Text); //将textboxscript的命令行传递给Worker_DoWork
}
catch (Exception error)
{
textBoxOutput.Text += String.Format("\r\nError in script : {0}\r\n", error.Message);
}
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
string scriptText = e.Argument.ToString( );
Runspace runspace = RunspaceFactory.CreateRunspace(); // 创建 Powershell runspace
runspace.Open(); // 打开runspace
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
e.Result = stringBuilder;
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//打算在这里显然dowork产生的任何输出信息,目前这个不工作
textBoxOutput.Text = e.UserState.ToString();
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("done");
}
}
}
------解决思路----------------------
在结束的事件
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
textBoxOutput.Text = e.UserState.ToString();
}
要这么写