Search code examples
powershellpowershell-cmdlet

How do I print objects to the console in format-list, but also return the objects as objects?


I have a cmdlet that returns custom objects.

I still want to return the objects, but when running the script I want to also output those objects to the console with format list- like how write-host writes to the console, but its output is not consumed by variable assignments.

So for example I want to be able to use it like this from the console:

$ArrayOfObjects = $ArrayOfIPsOrWhatever | MyCoolCmdlet.ps1

This is what the user sees in the console when running that command

name: myobj1
prop1: sdfsdfsdf
prop2: sldkjfss

name: myobj2
prop1: swerwew
prop2: kopkpjojpoj

BUT they can also use the array of objects (like this $ArrayOfObject[1..2])


Solution

  • You probably shouldn't be forcing the output on the caller like that; at least use Write-Verbose.

    But the way to do it is to just write the objects within your cmdlet with Write-Host or Write-Verbose, and return them to the output stream.

    To use the formatted output, you can do this mildly convoluted thing:

    $myObjects | Format-List | Out-String | Write-Verbose
    

    You should show your code and explain how it's not doing what you want.