>我有一个Exchange Powershell脚本,可以将电子邮件从一个帐户移动到另一个帐户。 当您通过Powershell调用代码时,它会为您提供实时数据统计信息。 我怎样才能捕获它并将其输入到一个文本框中,该文本框将提供该"实时提要"。提前感谢任何帮助。
public void RunPowerShell()
{
Cursor.Current = Cursors.WaitCursor;
RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();
PSSnapInException snapInException = null;
Runspace runSpace;
//create the runspace
runSpace = RunspaceFactory.CreateRunspace(rsConfig);
//insert try here
runSpace.Open();
//for exchange 2010 use "Microsoft.Exchange.Management.PowerShell.E2010"
rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.Admin", out snapInException);
//set up the pipeline to run the powershell command
Pipeline pipeLine = runSpace.CreatePipeline();
//create the scripts to use
String sScript = "Add-MailboxPermission -Identity " + FromEmailAccount.Text + " -User Administrator -AccessRights FullAccess";
String sScript1 = "Add-MailboxPermission -Identity " + ToEmailAccount.Text + " -User Administrator -AccessRights FullAccess";
String sScript2 = "Export-Mailbox -Identity " + FromEmailAccount.Text + " -TargetMailbox " + ToEmailAccount.Text + " -TargetFolder " + FromEmailAccount.Text + " -Confirm:$false";
//invoke the scripts
pipeLine.Commands.AddScript(sScript);
pipeLine.Commands.AddScript(sScript1);
pipeLine.Commands.AddScript(sScript2);
Collection<PSObject> commandResults = pipeLine.Invoke();
//loop through the results of the command and load the ?
foreach (PSObject results in commandResults)
{
richTextBox1.Text = results.ToString();
//MessageBox.Show(results.Properties["DisplayName"].Value.ToString(),@"Name");
}
//close the pipelin and runspace
pipeLine.Dispose();
runSpace.Close();
//create completed message
MessageBox.Show(@"Email migration is complete", @"Done");
Cursor.Current = Cursors.Default;
}
在行之后
pipeLine.Commands.AddScript(sScript2);
尝试添加
pipeLine.Commands.Add("out-string");
我认为这将获取所有输出(PSObjects)并将它们转换为字符串。这可能更容易在文本框中分析和显示。
下面是如何更新 GUI 的示例。在scriptText
变量中,我定义了两个PowerShell函数。您需要更改第一个函数,以具有启动邮箱导出的代码。然后,您需要更改第二个函数来查询导出并找出完成的百分比。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
using System.Threading;
using System.ComponentModel;
namespace PowerShellLiveUpdateExample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private BackgroundWorker bw = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
// Setup the BackgroundWorker
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textbox1.Text = (e.ProgressPercentage.ToString() + " %");
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
string scriptText = @"
function startExport() {
$script:finishtime = (get-date).addminutes(1)
}
function getPercentDone() {
$timeleft = new-timespan $(get-date) $finishtime
return [math]::truncate(100 - ($timeleft.totalseconds / 60) * 100)
}
startExport";
PowerShell psExec = PowerShell.Create();
psExec.AddScript(scriptText);
// Start the export
psExec.Invoke();
// Flush the currently added commands
psExec.Commands.Clear();
Collection<PSObject> results;
Collection<ErrorRecord> errors;
int percent = 0;
// Report on the export
while (percent < 100)
{
// Update every second
Thread.Sleep(1000);
psExec.AddScript("getPercentDone | out-string");
results = psExec.Invoke();
errors = psExec.Streams.Error.ReadAll();
foreach (PSObject obj in results)
{
Int32.TryParse(obj.ToString(), out percent);
worker.ReportProgress(percent);
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
textbox1.Text = "Canceled!";
}
else if (!(e.Error == null))
{
textbox1.Text = ("Error: " + e.Error.Message);
}
else
{
textbox1.Text = "Done!";
}
}
}
}
我想你想把PowerShell代码改成这样:
function startExport() {
$script:exportid = new-mailboxexportrequest -mailbox "John Doe" -filepath '\filesharejohn.doe.pst' -baditemlimit $baditemlimit
# Give the export some time to get settled
start-sleep 10
}
function getPercentDone() {
$export = get-mailboxexportrequest $script:exportid
$exportstats = $export | get-mailboxexportrequeststatistics
return $exportstats.PercentComplete
}
但我还没有测试过。