Erik
Erik

Reputation: 91

C# & Powershell: Not returning all Powershell results

I've been making a C# application that runs some Powershell stuff, the issue is that it doesn't seem to be be collecting the correct/all results of the Powershell commands.

The below code:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        List<string> results = RunScript("Get-ADUser testuser2 -Properties *");
        this.ShowMessageAsync("OK",results[0]);
    }

    private List<string> RunScript(string comand)
    {
        var powerShell = PowerShell.Create();
        powerShell.Runspace = runspace;
        powerShell.AddScript(comand);

        Collection<PSObject> results = powerShell.Invoke();
        List<string> resultsList = new List<string>();

        if (powerShell.Streams.Error.Count > 0)
        {
            this.ShowMessageAsync("Something went wrong!", "Check error log for details!");
            runspaceBox.AppendText(powerShell.Streams.Error[0] + "\r\n");
        }

        else
        {
            foreach (PSObject obj in results)
            {
                runspaceBox.AppendText(obj.ToString() + "\r\n");
                resultsList.Add(obj.ToString());
            }
        }
        return resultsList;
    }


Results in:

{CN=testuser2,DC=testdomain,DC=com}


Putting the command into Powershell directly results in the below:

PS C:\Users\Ultimate-V1> Get-ADUser testuser2 -Properties *

[A bunch of extra stuff above]

Description :

DisplayName : Test User2

DistinguishedName : CN=Test One,CN=Users,DC=testdomain,DC=com

Division :

DoesNotRequirePreAuth : False

[A lot of extra stuff below]


I've snipped a lot of the results out of the above command as it is very long.

What I can't work out is why it is only returning the Distinguished Name and not all of the results, this happens with some commands but not others. The command to return all AD groups on a user works fine for example.

If possible i'd love it to have EVERYTHING that the command returns, I will be formatting the resultsList later in the code.

Any help or pointers would be greatly appreciated!

Upvotes: 1

Views: 1559

Answers (1)

briantist
briantist

Reputation: 47792

Because you casted the result as a string, so you got a string representation of the complex object (whatever the result of the object's .ToString() method).

In PowerShell itself, it doesn't cast everything to a string to display it; it has various rules about how to display objects in general (usually a table or list format), and some types have specific formatters.

PetSerAl already answered in the comments, but the way to get a string representation of what PowerShell displays on the console is to send your output through Out-String:

powerShell.AddScript(comand).AddCommand("Out-String");

Upvotes: 2

Related Questions