从C#调用PowerShell的where-object

时间:2016-04-22 14:14:12

标签: c# powershell powershell-v4.0

如何从C#调用Where-Object(不使用过滤器)?我无法解析输出,因为我想将它传递给管道(不在下面的示例中)。

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\"");

这个问题类似于:PowerShell WhereObjectCommand from C#这个答案对我的问题来说还不够。

1 个答案:

答案 0 :(得分:0)

检查以下代码示例。我已根据您的要求更新了代码项目here中的示例。

注意:

  1. 使用\"
  2. 为您的命令添加引号,即脚本文本转义引号
  3. 要在脚本文本中添加{}大括号,请使用双花括号来转义String.Format(如{{}}

    // 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());
    }
    
  4. 当您将上述工作样本应用于您的问题时,您需要更改以下几行:

        //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);