Calling PowerShell's where-object from C#

自古美人都是妖i 提交于 2019-12-10 23:05:46

问题


How can I call Where-Object (without filter) from C#? I can't parse output, because I want to pass it to pipeline(not in example below).

PS:

Get-MailboxPermission username | Where-Object {$_.AccessRights -match "FullAccess" -and $_.IsInherited -eq $False}

C#:

Collection<PSObject> results = null;

Command command1 = new Command("Get-MailboxPermission");
command1.Parameters.Add("Identity", mailbox);
command1.Parameters.Add("DomainController", _domainController);
//I cannot use Filter. This is not possible in PS also.
//command1.Parameters.Add("Filter", "AccessRights -match \"FullAccess\"");

This question is simmilar to: PowerShell WhereObjectCommand from C# That answer is not enough for my problem.


回答1:


Check the below code sample. I have updated a sample from code project here as per your requirements.

Note:

  1. To add quotes to your command i.e. script text escape quotes by using \"
  2. To add { or } brace to the script text use double curly braces instead to escape it inside String.Format like {{ or }}

    // create Powershell runspace
    Runspace runspace = RunspaceFactory.CreateRunspace();
    
    // open it
    runspace.Open();
    
    // create a pipeline and feed it the script text
    Pipeline pipeline = runspace.CreatePipeline();
    
    //Getting all command variables
    string computerName = "YourComputerName";
    string matchingPattern = "con";
    
    //Create Script command
    String customScriptText = String.Format("Get-Process -ComputerName {0} | Where-Object {{$_.ProcessName -match \"{1}\"}}", computerName,matchingPattern);
    
    pipeline.Commands.AddScript(customScriptText);
    
    // add an extra command to transform the script output objects into nicely formatted strings
    // remove this line to get the actual objects that the script returns.
    pipeline.Commands.Add("Out-String");
    
    // execute the script
    Collection<PSObject> results = pipeline.Invoke();
    
    // close the runspace
    runspace.Close();
    
    // convert the script result into a single string
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    

When you apply the above working sample to your problem you will need to change couple of lines like below:

    //Getting all command variables
    string username = "YourUserName";

    //Create Script command
    String customScriptText = String.Format("Get-MailboxPermission {0} | Where-Object {{$_.AccessRights -match \"FullAccess\" -and $_.IsInherited -eq $False}}", username);


来源:https://stackoverflow.com/questions/36796176/calling-powershells-where-object-from-c-sharp

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