【问题标题】:How can I start a script in Exchange Management Shell from C#?如何从 C# 在 Exchange 命令行管理程序中启动脚本?
【发布时间】:2019-12-11 02:22:05
【问题描述】:

我正在创建一个网站,您可以使用该网站创建房间邮箱。单击“创建”后,将在 C# 中构建一个 PowerShell 脚本(作为字符串)。现在如何启动 Exchange 命令行管理程序并执行该脚本?

我试过了 Process.Start(EMSfilePath, scriptToBeExecuted),但是 EMS 是一个快捷方式(.lnk 文件),而 Process.Start 不喜欢这样。当我查看该快捷方式的目标时,我看到 powershell.exe 以几个参数启动。如果我尝试Process.Start("powershell.exe", coupleOfParameters),EMS 确实会打开,但是我现在不知道如何在其中传递我的脚本。请帮忙

【问题讨论】:

  • 您可以使用 PowerShell 类直接从 C# 执行 PowerShell 代码。我从未以这种方式尝试过任何与 Exchange 相关的脚本,但值得一看。
  • 是的,我现在正在查看,但它说缺少 api-ms-win-eventing-provider-l1-1-0.dll,如果我尝试添加该 dll它说“引用无效或不受支持”。
  • Office 365 还是本地 Exchange 服务器?

标签: c# powershell exchange-server


【解决方案1】:

我过去曾使用此 C# 示例代码来管理本地 Exchange Server:

using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security;


private static Runspace OpenExchangeManagementRunspace(
    string url,
    AuthenticationMechanism authenticationMechanism = AuthenticationMechanism.Kerberos,
    string userName = null,
    string password = null)
{
    Runspace runspace = null;

    WSManConnectionInfo shellConnection = null;

    PSCredential shellCred = null;

    // Username and password is optional when using Kerberos authentication
    if (!string.IsNullOrWhiteSpace(userName) &&
        !string.IsNullOrWhiteSpace(password))
    {
        var securePassword = ConvertToSecureString(password);
        shellCred = new PSCredential(userName, securePassword);
    }

    shellConnection = new WSManConnectionInfo(new Uri(url), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", shellCred);

    shellConnection.AuthenticationMechanism = authenticationMechanism;

    // This will take some time
    runspace = RunspaceFactory.CreateRunspace(shellConnection);
    runspace.Open();

    return runspace;
}


// USAGE:


// URL for Office365:
//     https://outlook.office365.com/powershell-liveid/
//
// URL for on-premises Exchange server:
//     http://hostname/powershell?serializationLevel=Full;clientApplication=MyAppName
//
using (Runspace remoteRunspace = OpenExchangeManagementRunspace("https://example.com/powershell?serializationLevel=Full;clientApplication=MyExampleAppName"))
using (PowerShell shell = PowerShell.Create())
{
    shell.Runspace = remoteRunspace;

    // Run some commands:
    shell
        .AddCommand("Get-Mailbox")
        .AddParameter("Identity", "example@example.com")
        .Invoke();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2011-04-04
    • 2011-02-08
    • 2017-09-02
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多