Exchange PowerShell commands through C#

前端 未结 2 948
你的背包
你的背包 2021-01-16 00:22

I am using C# to send PowerShell commands interacting with Exchange. I have a method called initconnection which sets up my connection to Exchange.

I ha

相关标签:
2条回答
  • 2021-01-16 00:47

    If "runspace" doesn't exist, that explains why the Get-Mailbox command is failing. Rather than managing a runspace, you could create a PowerShell instance in your initConnection method and use it wherever needed. Note this is shown with native code rather than a script.

    ps = PowerShell.Create(); 
    

    Set the execution policy.

    ps.ClearCommands()
     .AddCommand("Set-ExecutionPolicy")
     .AddParameter("Scope", "Process") 
     .AddParameter("ExecutionPolicy", "Unrestricted")    
     .AddParameter("Confirm", false)
     .AddParameter("Force", true)
     .Invoke();
    

    Create the credentials. Note that you should not need to call Get-Credential.

    SecureString pass;   
    var creds = new PSCredential(username, pass);
    

    Create and import a session.

    var newSession = ps.ClearCommands()
     .AddCommand("New-PSSession")
     .AddParameter("ConfigurationName", "Microsoft.Exchange")
     .AddParameter("ConnectionUri", "https://ps.outlook.com/powershell/")
     .AddParameter("Credential", creds)
     .AddParameter("Authentication", "Basic")
     .AddParameter("AllowRedirection", true)
     .Invoke();
    
    var session = newSession[0];
    var import = ps.ClearCommands()
     .AddCommand("Import-PSSession")
     .AddParameter("Session", session)
     .Invoke();
    

    ps.ClearCommands() is an extension method, added so it can be chained with AddCommand(), AddParameter(), etc:

    public static PowerShell ClearCommands(this PowerShell ps)
    {
        if (ps.Commands != null)
            ps.Commands.Clear();
    
        return ps;
    }
    

    Use it in Get_Mailboxes()

    protected void Get_Mailboxes(object sender, EventArgs e) {
    
      var commandResults = ps.ClearCommands().AddCommand("Get-Mailbox").Invoke();
      StringBuilder sb = new StringBuilder();
      ArrayList boxesarray = new ArrayList();
    
      foreach (PSObject ps in commandResults)
      {
          boxesarray.Add(ps.Properties["Alias"].Value.ToString());
      }
    
      boxes.DataSource = boxesarray;
      boxes.DataBind();
    }
    

    When you close the app, or somewhere appropriate:

    ps.ClearCommands()
     .AddCommand("Get-PSSession")
     .AddCommand("Remove-PSSession")
     .Invoke();
    
    ps.Dispose();
    
    0 讨论(0)
  • 2021-01-16 00:52

    You have to add the Exchange snap-in to your runspace. Take a look at Exchange for developers.

    0 讨论(0)
提交回复
热议问题