2014-02-06 27 views
2

我正嘗試在C#中編寫代碼,該代碼通過Power Shell命令從用戶處獲取郵箱詳細信息。如何從.Net程序運行Import-PSSession

電源外殼命令腳本是:

Import-PSSession -session (New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://myServer.myDomain.com/Powershell) 
Get-Mailbox -Identity helpdesk 

運行該腳本確定從PowerShell中。

現在我的目標是使用C#運行它。

這是我的函數:

private void button1_Click(object sender, EventArgs e) 
{ 
    m_RunSpace = RunspaceFactory.CreateRunspace(); 

    m_RunSpace.Open(); 

    Pipeline pipeLine = m_RunSpace.CreatePipeline(); 

    Command newSession = new Command("New-PSSession"); 
    newSession.Parameters.Add("-ConfigurationName", "Microsoft.Exchange"); 
    newSession.Parameters.Add("-ConnectionUri", "http://myServer.myDomain.com/Powershell"); 

    Command createSessionForExch = new Command("Import-PSSession"); 
    createSessionForExch.Parameters.Add("-Session", newSession); 

    Command getMailbox = new Command("Get-Mailbox"); 
    getMailbox.Parameters.Add("-Identity", "helpdesk"); 

    pipeLine.Commands.Add(createSessionForExch); 
    pipeLine.Commands.Add(getMailbox); 

    Collection<PSObject> commandResults = pipeLine.Invoke(); 

    foreach (PSObject cmdlet in commandResults) 
    { 


    } 
} 

但是我收到一個錯誤「獲取郵箱」命令不被識別: enter image description here

大概是因爲進口PSSession中沒有被正確invok 。

我需要幫助如何正確地從C#

+0

是用戶帳戶運行腳本的一個memeber Exchange中可以管理郵箱的RBAC角色?否則,導入會話時將無法獲取它的cmdlet。 – mjolinor

+0

是的。 用戶運行腳本有權限。 當我在PowerShell上運行它時,它工作正常。 當我試圖在C#上實現它時,我收到一個錯誤。 我想我沒有正確實施它。 – E235

+0

你有沒有找到辦法做到這一點? –

回答

0

使用WSManConnectionInfo類提供URI,模式運行命令導入-PSSession可打開遠程runspace.Please找到代碼:

private static string CreateConnection() 
    { 
     Runspace remoteRunspace = null; 



     openRunspace(
      "https://pod51057psh.outlook.com/powershell-liveid?PSVersion=3.0", 
      "http://schemas.microsoft.com/powershell/Microsoft.Exchange", 
      @"[email protected]", 
      "xxxxx", 
      ref remoteRunspace 
     ); 

     // Command getLicenseCommand = new Command("Get-MsolAccountSku"); 
      //Command activityCommand = new Command("Get-GroupActivityReport"); 
      //activityCommand.Parameters.Add(new CommandParameter("ReportType", "Daily")); 
      //activityCommand.Parameters.Add(new CommandParameter("StartDate", "03/4/2014")); 
      //activityCommand.Parameters.Add(new CommandParameter("EndDate", "03/27/2014")); 

     Command activityCommand = new Command("Get-Mailbox"); 
     activityCommand.Parameters.Add("-Identity", "xxx"); 

     StringBuilder stringBuilder = new StringBuilder(); 
     using (PowerShell powershell = PowerShell.Create()) 
     { 
      powershell.Runspace = remoteRunspace; 
      powershell.Commands.AddCommand(activityCommand); 

      powershell.Invoke(); 
      var results = powershell.Invoke(); 
      remoteRunspace.Close(); 
      foreach (PSObject obj in results) 
      { 
       stringBuilder.AppendLine(obj.ToString()); 
      } 
     } 
     remoteRunspace.Close(); 
     return stringBuilder.ToString(); 


    } 
    public static void openRunspace(string uri, string schema, string username, string livePass, ref Runspace remoteRunspace) 
    { 
     System.Security.SecureString password = new System.Security.SecureString(); 
     foreach (char c in livePass.ToCharArray()) 
     { 
      password.AppendChar(c); 
     } 
     PSCredential psc = new PSCredential(username, password); 
     WSManConnectionInfo rri = new WSManConnectionInfo(new Uri(uri), schema, psc); 

     rri.AuthenticationMechanism = AuthenticationMechanism.Basic; 

     remoteRunspace = RunspaceFactory.CreateRunspace(rri); 
     remoteRunspace.Open(); 
    } 
+0

它看起來像你在正確的方式。 我試過了,但沒有成功從用戶處獲取有關郵箱的信息。你可以看到打印屏幕: ![PrintScreen](http://s30.postimg.org/gu3rvzppd/powershell_Exchange.png)。 結果計數爲零,所以沒有信息。 您可以在附近看到該命令從powershell運行。 我在operRunspace命令中添加了我的用戶名和密碼。 – E235

1

希望,你已經找到了解決方案。如果沒有,請給這個代碼試試:

String url = "http://" + ExchangeServerName + "/powershell?serializationLevel=Full"; 
     System.Uri uri = new Uri(url); 
     Console.WriteLine(url); 
     System.Security.SecureString securePassword = String2SecureString(password); 

     System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword); 


     Runspace runspace = System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(); 

     PowerShell powershell = PowerShell.Create(); 
     PSCommand command = new PSCommand(); 
     command.AddCommand("New-PSSession"); 


     command.AddParameter("ConfigurationName", "Microsoft.Exchange"); 
     command.AddParameter("ConnectionUri", uri); 

     command.AddParameter("Credential", creds); 
     command.AddParameter("Authentication", Authentication); 
     //PSSessionOption sessionOption = new PSSessionOption(); 
     //sessionOption.SkipCACheck = true; 
     //sessionOption.SkipCNCheck = true; 
     //sessionOption.SkipRevocationCheck = true; 
     //command.AddParameter("SessionOption", sessionOption); 

     powershell.Commands = command; 

     try 
     { 
      runspace.Open(); 

      powershell.Runspace = runspace; 

      Collection<PSSession> result = powershell.Invoke<PSSession>(); 

      foreach (ErrorRecord current in powershell.Streams.Error) 
       Console.WriteLine("The following Error happen when opening the remote Runspace: " + current.Exception.ToString() + 
                      " | InnerException: " + current.Exception.InnerException); 

      if (result.Count != 1) 
       throw new System.Exception("Unexpected number of Remote Runspace connections returned."); 

      // Set the runspace as a local variable on the runspace 
      powershell = PowerShell.Create(); 

      command = new PSCommand(); 
      command.AddCommand("Set-Variable"); 
      command.AddParameter("Name", "ra"); 
      command.AddParameter("Value", result[0]); 
      powershell.Commands = command; 
      powershell.Runspace = runspace; 
      powershell.Invoke(); 

      // First import the cmdlets in the current runspace (using Import-PSSession) 
      powershell = PowerShell.Create(); 
      command = new PSCommand(); 
      //command.AddScript("Import-PSSession $ra"); 
      command.AddScript("Invoke-Command -ScriptBlock { Get-Mailbox -Identity:" + MailBoxName + " } -Session $ra"); 
      powershell.Commands = command; 
      powershell.Runspace = runspace; 
      //powershell.Commands.AddCommand("Import-Module").AddArgument("activedirectory"); 
      powershell.Invoke(); 

      //command = new PSCommand(); 
      //command.AddCommand("Get-Mailbox"); 

      ////Change the name of the database 

      //command.AddParameter("Identity", ""); 

      //powershell.Commands = command; 
      //powershell.Runspace = runspace; 


      Collection<PSObject> results = new Collection<PSObject>(); 
      results = powershell.Invoke();