0

I'm trying to call the following PS script from C#:

Get-MailboxDatabase -IncludePreExchange2007 -Status | Where-Object {$_.Server -eq 'myserver'}

I have managed to execute the first part before the pipe using this code:

  public void Test()
  {
     using (Pipeline pipeline = _runspace.CreatePipeline())
     {
        var cmd1 = new Command("Get-MailboxDatabase");
        cmd1.Parameters.Add("IncludePreExchange2007");
        cmd1.Parameters.Add("Status");

        var cmd2 = new Command("Where-Object");
        //how do I script {$_.Server -eq 'myserver'} ???

        pipeline.Commands.Add(cmd1);
        //pipeline.Commands.Add(cmd2);

        Collection<PSObject> result = pipeline.Invoke();
     }
  }

but how do I script the second part for Where-Object???

2 Answers 2

2

You can simply use LINQ:

result.Where(p => (string)p.Properties["Server"].Value == "myserver"));
Sign up to request clarification or add additional context in comments.

1 Comment

you're right, probably I won't get better performance as this filter will be applied after i get all the results from the first command
0

I am updating this thread in case another user visits this question.

To enhance the performance you can perform filtering in the PowerShell itself and can use Where-Object there. I have provided the answer here: Calling PowerShell's where-object from C#

Essentially, you will need to use Add Script instead of adding command like below:

    //Getting all command variables
    string myServer = "ServerName";

    //Create Script command
    String customScriptText = String.Format("Get-MailboxDatabase -IncludePreExchange2007 -Status | Where-Object {{$_.Server -eq \"{0}\"}}", myServer);

    pipeline.Commands.AddScript(customScriptText);

Note to escape { and } using double curly braces i.e. {{ and }}. Also escape quotes as \" using back slash in the String.Format method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.