PowerShell WhereObjectCommand from C#

点点圈 提交于 2019-12-24 20:06:28

问题


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???


回答1:


You can simply use LINQ:

result.Where(p => (string)p.Properties["Server"].Value == "myserver"));



回答2:


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.



来源:https://stackoverflow.com/questions/14104222/powershell-whereobjectcommand-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!