Execute exchange management shell cmdlets using C#? RRS feed

  • Question

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


    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


    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

    Monday, September 1, 2014 4:40 AM


  • All you need to do is enumerate through the results collection and all the properties will be there eg

                var results = pipeline.Invoke();
                foreach (PSObject result in results) {

    Also instead of using Where-Object its better to use Filter as this will execute at the server

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


    • Edited by Glen ScalesMVP Tuesday, September 2, 2014 6:42 AM
    • Marked as answer by Harry_42 Thursday, September 4, 2014 6:07 AM
    Tuesday, September 2, 2014 6:23 AM