gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:11 24 4
gpt4 key购买 nike

如何从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com