Exchange PowerShell commands through C#

老子叫甜甜 提交于 2019-12-01 12:54:32
Alexis Mathieu

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

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!