简体   繁体   English

将Powershell结果获取到C#列表中

[英]Get Powershell result into C# List

I have the following PS Script(built with the PowerShell C# object): 我有以下PS脚本(使用PowerShell C#对象构建):

    List<string> powershellResults = new List<string>();
    foreach (string str in PowerShell.Create().AddScript("Get-ADGroupMember \"Domain Users\" -Server \"Server\" | Select-Object -Property \"Name\" | Format-List").AddCommand("Out-String").Invoke<String>())
    {

        powershellResults.Add(str);


    }

However, I quickly found that instead of looping through the returned PS list, it just sticks the entire output of the PS List into the C# container(so there is only 1 entry that looks like: 但是,我很快发现,与其循环遍历返回的PS列表,不如将PS列表的整个输出粘贴到C#容器中(因此只有1个条目看起来像:

Name : Alf
Name : Jim
Name : Carrol

How can I get PS to return each result individually? 如何获得PS分别返回每个结果? Or will I have to do some string manipulation in C# on the PS output? 还是我必须在PS输出的C#中做一些字符串操作?

I think you're doing too much in the PowerShell script part. 我认为您在PowerShell脚本部分中做得太多。 Try this: 尝试这个:

var list = new List<string>();
using (var ps = PowerShell.Create()) {
    ps.AddScript("Get-ADGroupMember 'Domain Users' -Server Server | Select-Object -Property Name");
    var results = ps.Invoke();
    foreach (var result in results) {
        list.Add(result.Name);
    }
}

In fact, you could probably even lose the Select-Object part of the pipeline. 实际上,您甚至可能会丢失管道的“选择对象”部分。 PowerShell will return the .NET objects to your program and you can select the properties you're interested in. PowerShell将.NET对象返回到您的程序,您可以选择感兴趣的属性。

BTW when you use Out-String the entire output is accumulated into a single string. 顺便说一句,当您使用Out-String ,整个输出将累积为一个字符串。 If you want Out-String to produce an array of strings use the -Stream parameter. 如果要让Out-String生成字符串数组,请使用-Stream参数。

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

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