c# - 从 C# 调用 PowerShell 的 where-object

标签 c# powershell powershell-4.0

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

附言:

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#这个答案不足以解决我的问题。

最佳答案

检查下面的代码示例。我已经更新了代码项目中的示例 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());
    }
    

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

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

关于c# - 从 C# 调用 PowerShell 的 where-object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36796176/

相关文章:

entity-framework - 从云服务项目的 powershell 运行 migrate.exe?

powershell - Powershell 中的 PsObject 数组

PowerShell 提示选择

c# - 混合通用方法和扩展方法

c# - 我应该如何处理 Entity Framework 中潜在的大量编辑?

c# - 将对象列表保存到 XML 文件并使用 C# 加载该列表的最佳方法是什么?

powershell - Foreach循环在PowerShell中不起作用

powershell - 使用DisplayNames从文本文件获取SamAccountName

powershell - 如何更快地过滤带有某些字符的文件行?

c# - 如何确定是否在面板上执行了右键单击?