c#中的Exchange Powershell

时间:2015-07-02 23:01:40

标签: c# powershell exchange-server

我在c#中有一堆powershell命令但是有一个返回0结果而我无法弄明白,所以凭借互联网的力量,我希望你们有答案。

运行电源的我的c#代码如下

m

我可以确认snapin正确加载,如果我手动运行powershell命令就可以了,我确认没有权利问题

这是powershell命令的原始格式

internal static List<ExchangeMailboxes> ExchangeMailboxList(string snapIn)
        {
            List<ExchangeMailboxes> data = new List<ExchangeMailboxes>();
            StringBuilder stringBuild = new StringBuilder();
            stringBuild.AppendLine("$script:WarningPreference = 'SilentlyContinue'");
            stringBuild.AppendLine(
                "Get-Mailbox -ResultSize Unlimited | Get-MailboxStatistics | Select DisplayName,@{name='TotalItemSize';expression={[math]::Round((($_.TotalItemSize.Value.ToString()).Split('(')[1].Split(' ')[0].Replace(',','')/1GB),2)}},@{name='TotalDeletedItemSize';expression={[math]::Round((($_.TotalDeletedItemSize.Value.ToString()).Split('(')[1].Split(' ')[0].Replace(',','')/1GB),2)}}");
            using (PowerShell inst = PowerShell.Create())
            {
                inst.AddScript("Add-PSSnapin " + snapIn)
                    .AddScript(stringBuild.ToString());
                Collection<PSObject> results = inst.Invoke();
                foreach (PSObject obj in results)
                {
                    data.Add(new ExchangeMailboxes()
                    {
                        Name = obj.Members["DisplayName"].Value.ToString(),
                        InboxSize = obj.Members["TotalItemSize"].Value.ToString(),
                        DeletedSize = obj.Members["TotalDeletedItemSize"].Value.ToString()
                    });
                }
            }
            return data;
        } 

1 个答案:

答案 0 :(得分:1)

与Exchange 2010及更新版本进行交互的推荐方法是使用microsoft.exchange配置打开到http://servername/powershell的会话:

$ExSession = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri ‘http://ExServer1.contoso.com/PowerShell/?SerializationLevel=Full’ -Credential $Credentials –Authentication Kerberos

我从来没有尝试过使用c#代码进行远程处理,但我想它应该与你现在所做的不同(当然除了powershell代码本身)。由于您在Exchange中与各种“大小”属性进行交互,因此仍建议在本地安装管理工具,否则这些值不会正确序列化/反序列化(您将在该主题的serverfault上找到其他帖子)。