Powershell – Printing object properties in Powershell

powershell

When working in the interactive console if I define a new object and assign some property values to it like this:

$obj = New-Object System.String
$obj | Add-Member NoteProperty SomeProperty "Test"

Then when I type the name of my variable into the interactive window Powershell gives me a summary of the object properties and values:

PS C:\demo> $obj
SomeProperty                                                                                                                                                                                  
------------                                                                                                                                                                                  
Test

I basically want to do just this but from within a function in a script. The function creates an object and sets some property values and I want it to print out a summary of the object values to the Powershell window before returning. I tried using Write-Host within the function:

Write-Host $obj

But this just output the type of the object not the summary:

System.Object

How can I have my function output a summary of the object's property values to the Powershell window?

Best Answer

Try this:

Write-Host ($obj | Format-Table | Out-String)

or

Write-Host ($obj | Format-List | Out-String)