2013-08-22 127 views
1

我正在C#中編寫一個WinForms應用程序,最終將以.pst格式將Exchange 2010郵箱遷移到文件位置(pstStore)。該表格由一組文本框,組合框和單選按鈕組成。完成這項工作的命令是New-MailboxExportRequest -Mailbox ... -FilePath ...按鈕單擊後。將C#變量傳遞給Powershell引擎

我正在訪問Exchange管理外殼並使用運行空間傳遞該cmdlet和參數。在參數(-Mailbox和-FilePath)中,我想傳遞文本框和組合框的值。我如何在C#中執行此操作?

僅供參考...我使用相同的代碼來填充交換數據庫中所有郵箱的組合框。因此,代碼適用於此目的,所以我想我也可以使用它將一些變量傳入到AddParameter方法中。

下面是從點擊事件代碼:

InitialSessionState iss = InitialSessionState.CreateDefault(); 
    PSSnapInException warning;   iss.ImportPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010",out warning); 
    using (Runspace myrunspace = RunspaceFactory.CreateRunspace(iss)) 
    { 
     myrunspace.Open();         
     using (PowerShell powershell = PowerShell.Create())      
     {    powershell.AddCommand("Microsoft.Exchange.Management.PowerShell.E2010\\New-MailboxExportRequest") 
    powershell.AddParameter("Mailbox", "UserMailbox"); 
    powershell.AddParameter("FilePath", "ExchAdmin"); 
    powershell.AddParameter("",""); 
    powershell.Runspace = myrunspace; 
    Collection<PSObject> results = null; 
    try 
    { 
     results = powershell.Invoke(); //Runs the cmdlet synchronously 
    } 
    catch (RuntimeException ex) 
    { 
     foreach (PSObject thisResult in results) 
     { 
      lstBoxStatus.Items.Add(thisResult); //sending the result to a status window 
     } 
    }     
    myrunspace.Close(); 
    } 

回答

1

當你調用AddParameter重載有兩個參數,第二個是值。只需在此處使用C#變量的名稱即可。例如:

string mailbox = _mailBoxTextBox.Text; 
... 
powershell.AddParameter("Mailbox", mailbox); 
+0

現在看起來似乎有訣竅。我有錯誤範圍內的變量。一旦我確定參數被排除在外。還有更多的工作要做,所以它不是太笨重,但是,爲了清晰起見。 – user2704769