Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default output Formatting of Powershell to use Format-Table -autosize?

How can I enforce powershell to use

Format-Table -auto

as a default formatting when writing a returned array of objects to the console? Thanks

like image 418
pencilCake Avatar asked Mar 13 '23 12:03

pencilCake


1 Answers

If you are OK calling the cmdlet every time and if you have at least PowerShell v3.0 then you can set a $PSDefaultParameterValues which you can read more about at about_Parameters_Default_Values.

The syntax that would satisfy your need would be:

$PSDefaultParameterValues=@{"<CmdletName>:<ParameterName>"="<DefaultValue>"}

So we add in the switch by setting it to $true.

$PSDefaultParameterValues = @{"Format-Table:Autosize"=$true}

To remove this you would have to do it much the same as you would a hashtable element

$PSDefaultParameterValues.Remove("Format-Table:Autosize")

From the aforementioned article here is some pertinent information as to how to deal with these.

$PSDefaultParameterValues is a preference variable, so it exists only in the session in which it is set. It has no default value.

To set $PSDefaultParameterValues, type the variable name and one or more key-value pairs at the command line.

If you type another $PSDefaultParameterValues command, its value replaces the original value. The original is not retained.

To save $PSDefaultParameterValues for future sessions, add a $PSDefaultParameterValues command to your Windows PowerShell profile. For more information, see about_Profiles.


Outside of that I am not sure as it would be difficult to change in a dynamic sense. You would want to be sure that data sent to the stream appears on screen in the same way that format-table -auto does but you would have to make sure that it does not affect data so that you could not capture it or send it down the pipe.

You are looking at creating custom output format files, like Frode F. talks about, then you would need to consider looking at about_Format.ps1xml but you would need to configure this for every object that you would want to display this way.

FileSystem.format.ps1xml, for example, would govern the output from Get-ChildItem. Format-Table is more dynamic and I don't think you can say just use Format-Table in that file.

like image 86
Matt Avatar answered Apr 07 '23 18:04

Matt