繁体   English   中英

从C#调用PowerShell的where对象

[英]Calling PowerShell's where-object from C#

如何从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 from C#WhereObjectCommand这个答案不足以解决我的问题。

检查以下代码示例。 我已经更新从代码项目的样本在这里按您的要求。

注意:

  1. 要在命令中添加引号,即使用\\"脚本文本转义引号
  2. 要将{}大括号添加到脚本文本中,请使用双大括号将其放到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()); } 

当您将上述工作示例应用于问题时,您将需要更改以下几行:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM