PowerShell WhereObjectCommand from C#

2019-09-08 08:32发布

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条回答
何必那么认真
2楼-- · 2019-09-08 08:51

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.

查看更多
虎瘦雄心在
3楼-- · 2019-09-08 09:01

You can simply use LINQ:

result.Where(p => (string)p.Properties["Server"].Value == "myserver"));
查看更多
登录 后发表回答