3

I need to convert PSObject to String(). Is there any standard way available to do this task? Somehow powershell also does ToString() or spits out a readable stream on ISE console. I used PSSerializer.Serialize(PSObject) but it serializes everything. I want in my application seemlessly everything shown in a way the way Powershell does.

Is there anyway to convert PSObject to a.readable string. At the moment when I use following line of code

PSObject.ToString()

or

PSObject.BaseObject.ToString()

both just print out complete type name. ( e.g. "System.Collection.HashTable" ) But I want complete displayed contents to see the way powershell exposes.C#

pfx
  • 20,323
  • 43
  • 37
  • 57
Usman
  • 2,742
  • 4
  • 44
  • 82

1 Answers1

1

You could get PowerShell to format it for you.

foreach (PSObject obj in myPsObjects)
{
    var formattedObj =
        System.Management.Automation.PowerShell
        .Create()
        .AddCommand("Write-Output").AddArgument(obj)
        .AddCommand("Out-String")
        .Invoke();

    string message = string.Join(" ", formattedObj);
    Console.Write(message);
}
intrepidis
  • 2,870
  • 1
  • 34
  • 36