通过C#交换PowerShell命令 [英] Exchange PowerShell commands through C#

查看:87
本文介绍了通过C#交换PowerShell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#发送与Exchange交互的PowerShell命令.我有一个名为initconnection的方法,该方法可以建立与Exchange的连接.

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

我有另一种方法,当我单击建立连接后将向Powershell发送命令的按钮时,我会调用该方法.但是,我无法继续创建的连接.当我尝试运行命令时,提示未找到该命令.很有可能是因为它没有交换cmdlet.

I have another method that I call when I click a button that will send a command to powershell after the connection is established. However I am not able to continue the created connection. When I try to run a command it says the command is not found. More than likely because it doesn't have the exchange cmdlets.

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

runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Set-ExecutionPolicy Unrestricted -Scope process -Force;$password = ConvertTo-SecureString -AsPlainText -Force " + password + ";$mycred = new-object -typename System.Management.Automation.PSCredential -argumentlist " + username + ",$password;$LiveCred = Get-Credential -Credential $mycred; $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic –AllowRedirection; Import-PSSession $Session");
// pipeline.Commands.Add("Out-String");

pipeline.Invoke();
mpeAdd.Hide();

这是用于创建连接的initconnection方法.

This is the initconnection method that creates the connection.

protected void Get_Mailboxes(object sender, EventArgs e) {

    PowerShell powershell = PowerShell.Create();
    PSCommand command = new PSCommand();
    command = new PSCommand();
    command.AddCommand("Get-Mailbox");

    powershell.Commands = command;
    powershell.Runspace = runspace; //Also it says runsapce doesn't exist in this context.
    Collection<PSObject> commandResults = powershell.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();
}

这是我创建连接后单击按钮时调用的方法,但是它不起作用.

This is my method I call when I click a button after the connection is create however it is not working.

推荐答案

您必须将Exchange管理单元添加到您的运行空间中.看看 交换开发人员 .

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

这篇关于通过C#交换PowerShell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆