Daniel Martin
Daniel Martin

Reputation: 570

Get Powershell result into C# List

I have the following PS Script(built with the PowerShell C# object):

    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:

Name : Alf
Name : Jim
Name : Carrol

How can I get PS to return each result individually? Or will I have to do some string manipulation in C# on the PS output?

Upvotes: 0

Views: 3246

Answers (1)

Keith Hill
Keith Hill

Reputation: 201852

I think you're doing too much in the PowerShell script part. 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.

BTW when you use Out-String the entire output is accumulated into a single string. If you want Out-String to produce an array of strings use the -Stream parameter.

Upvotes: 3

Related Questions