Search code examples
c#powershell-cmdletexchange-management-shell

Execute exchange management shell cmdlets using C#?


I am trying to execute the following exchange management shell cmdlets using C# in order to get total number of mailbox on the server.

cmdlets:-

Get-mailbox -resultsize unlimited 

My code snippet is as following

        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 
        }    

The above code gives the desired result i.e. total number of mailboxes.But how can i select some properties of all the mailboxes i.e. how can i execute the following cmdlets

cmdlets:

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

Please guid, how can i execute the above given cmdlets... Thank you


Solution

  • You need to list some properties that you specify in select-object, you can do this like below

    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);
    }
    

    And it is good to use Filter instead of where-object, this can be run as below

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