0

目标:使用 Visual Basic 或 C# 或 .NET 提供与 Exchange 命令行管理程序交互的 Web 服务,向其发送命令以运行 cmdlet,并以 XML 形式返回结果。(请注意,我们可以使用任何语言来编写服务,但由于它是 Windows Box 并且我们有 Visual Studio 2008,似乎最简单的解决方案就是使用它来创建 VB/.NET Web 服务。确实,它这样做很容易,只需指向并单击即可。)

问题:如何从 Web 服务运行 Exchange 命令行管理程序 cmdlet,例如 Get-DistributionGroupMember "Live Presidents"

似乎我们应该能够创建一个运行 cmdlet 的 PowerShell 脚本,并且能够从命令行调用它,因此只需从程序中调用它。这听起来正确吗?如果是这样,我将如何处理?谢谢。答案可能与语言无关,但 Visual Basic 可能是最好的,因为我在其中加载了测试 Web 服务。

4

2 回答 2

1

改编自 MSDN http://msdn.microsoft.com/en-us/library/exchange/bb332449(v=exchg.80).aspx的实际代码可能很棘手,因为您必须获得正确的权限并在其上运行具有所有 Exchange 插件的机器:

using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation.Runspaces;
using System.Reflection;

    public static Runspace GetExchangeRunspace()
    {
        return GetExchangeRunspace("");
    }
    public static Runspace GetExchangeRunspace(string snapIn)
    {
        string consoleFilePath = (ScriptEngine.GetExchangeAssemblyPath() 
            + "bin\\exshell.psc1").Replace("Exchange Server", "EXCHAN~1");
        Response.Write("<br/>" + consoleFilePath);
        PSConsoleLoadException warnings = null;
        RunspaceConfiguration runspaceConfiguration 
            = RunspaceConfiguration.Create(consoleFilePath, out warnings);
        if ((snapIn + "").Trim().Length > 0)
        {
            PSSnapInException warning = null;
            Response.Write("<br/>Start AddPSSnapIn..." + snapIn);
            Response.Write("<br/>" 
                + runspaceConfiguration.AddPSSnapIn(snapIn, out warning));
            Response.Write("<br/>" + warning);
        }
        return RunspaceFactory.CreateRunspace(runspaceConfiguration);
    }

    private static string GetExchangeAssemblyPath()
    {
        string path = "";
        try
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(
                "SOFTWARE\\Microsoft\\ExchangeServer\\v14\\Setup"); // or your version
            if (key != null)
            {
                path = Path.GetFullPath(string.Concat(key.GetValue("MsiInstallPath")));
                Response.Write(path);
            }
        }
        catch (Exception ex) { }
        return path;
    }
于 2013-09-04T17:39:00.717 回答
0

好吧,没有得到答案,但有点想通了。我在运行 64 位 PowerShell 时遇到问题,但最终升级到 Exchange 2010 并使用 C#,然后就不再有问题了。

简短的回答是在 Visual Studio 中创建一个新的 PowerShell 应用程序,然后添加对 System.Management.Automation dll 的引用。这允许您为 Powershell 设置命名空间并对其进行调用。http://msdn.microsoft.com/en-us/library/system.management.automation(VS.85).aspx您使用可用的管道类http://msdn.microsoft.com/en-us创建管道/library/system.management.automation.runspaces.pipeline(VS.85).aspx以便通过管道返回您的命令。然后你把你的命令放进去,如果需要的话添加参数。运行该应用程序,它将返回您在 PowerShell 中调用的 cmdlet 的结果,您可以从那里开始。

于 2010-05-02T02:53:35.460 回答