0

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?

1
  • Out-String outputs a string, not a string array what i think you are expecting Commented Jan 13, 2015 at 17:11

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.