How to change default output Formatting of Powersh

2019-04-11 13:16发布

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

1条回答
放我归山
2楼-- · 2019-04-11 14:07

If you 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.

查看更多
登录 后发表回答