【问题标题】:Execute exchange management shell cmdlets using C#?使用 C# 执行交换管理 shell cmdlet?
【发布时间】:2014-10-23 05:11:28
【问题描述】:

我正在尝试使用 C# 执行以下 Exchange Management Shell cmdlet,以获取服务器上的邮箱总数。

小命令:-

Get-mailbox -resultsize unlimited 

我的代码 sn-p 如下

        PSCredential credential = new PSCredential("Administrator", securePassword); // the password must be of type SecureString
        WSManConnectionInfo connectionInfo = new WSManConnectionInfo(connectTo,schemaURI, credential);
        connectionInfo.MaximumConnectionRedirectionCount = 5;
        connectionInfo.SkipCACheck = true;
        connectionInfo.SkipCNCheck = true;

        try
        {
            Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo);
            remoteRunspace.Open();
            var command = new Command("Get-mailbox");
            command.Parameters.Add("resultsize", "unlimited");
            var pipeline = remoteRunspace.CreatePipeline();
            pipeline.Commands.Add(command);
            // Execute the command
            var results = pipeline.Invoke();
            MessageBox.Show(results.Count.ToString());
            remoteRunspace.Dispose();
        }
        catch (Exception ex)
        {
            //Handle error 
        }    

上面的代码给出了想要的结果,即邮箱总数。但是我如何选择所有邮箱的一些属性,即如何执行以下 cmdlet

小命令:

Get-mailbox | select-object DisplayName, PrimarySmtpAddress, ForwardingAddress, alias, identity, legacyexchangeDN | where-object {$_.ForwardingAddress -ne $Null}

请指导,我怎样才能执行上面给定的 cmdlet... 谢谢

【问题讨论】:

    标签: c# cmdlets exchange-management-shell


    【解决方案1】:

    你需要列出一些你在 select-object 中指定的属性,你可以像下面那样做

    var results = pipeline.Invoke();
    foreach (PSObject result in results) {
    Console.WriteLine(result.Properties["DisplayName"].Value);
    Console.WriteLine(result.Properties["PrimarySmtpAddress"].Value);
    Console.WriteLine(result.Properties["ForwardingAddress"].Value);
    Console.WriteLine(result.Properties["alias"].Value);
    Console.WriteLine(result.Properties["identity"].Value);
    Console.WriteLine(result.Properties["legacyexchangeDN "].Value);
    }
    

    而且最好用Filter代替where-object,这样可以运行如下

    command.Parameters.Add("Filter", "{forwardingaddress -ne $null}");
    

    【讨论】:

      猜你喜欢
      • 2011-12-11
      • 2011-02-12
      • 2015-06-06
      • 2021-11-21
      • 1970-01-01
      • 2020-04-03
      • 2017-06-01
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多