Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell output formatting

Tags:

c#

powershell

I am developing a Powershell Cmdlet using C#, and I was wondering if there's a way of controlling the formatting of the objects I write to Powershell in the Cmdlet itself. Basically, I have objects with too many properties to display easily on the screen, and my Cmdlet is sending those to Powershell with WriteObject()

I would like users of my cmdlets to be able to run them and, in the Powershell console, read the data returned as they would have done using the command prompt. Unfortunately, the number of properties Powershell is trying to fit in columns means most are truncated, and when I add more it gives each property its own line which is worse.

I've seen things which allow the user to format the data appropriately, but nothing that allows the developer to set a default. Basically what I want is something like an Attribute I can apply to each property of the objects being pumped through to Powershell which tells Powershell whether to display each property or not (assuming the user has set no other formatting options).

(I've tried making them public fields instead of properties too, and Powershell still shows them)

like image 789
Neil Avatar asked Mar 17 '12 18:03

Neil


People also ask

How do I display output in a table format in PowerShell?

Using Format-Table for Tabular Output. If you use the Format-Table cmdlet with no property names specified to format the output of the Get-Process command, you get exactly the same output as you do without a Format cmdlet. By default, PowerShell displays Process objects in a tabular format.

How do I show output in PowerShell?

The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.


1 Answers

I'm assuming you're using PowerShell 2.0.

If your module is called MyModule, you can create a MyModule.Format.ps1xml file alongside it to describe what properties are displayed by default by Format-List, Format-Table, etc. See Get-Help about_Format.ps1xml and Formatting File Overview for more information.

To link your formatting file to your module, you would create a module manifest and define the FormatsToProcess item. The New-ModuleManifest cmdlet can get you started with this.

like image 107
Lance U. Matthews Avatar answered Sep 18 '22 23:09

Lance U. Matthews