使用C#执行Exchange管理shell cmdlet?

时间:2014-08-29 08:01:59

标签: c# cmdlets exchange-management-shell

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

小命令: -

Get-mailbox -resultsize unlimited 

我的代码段如下

        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 ... 谢谢

1 个答案:

答案 0 :(得分: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}");