How To Create Aligned Headers with PowerShell

Reporting and writing log files is a regular task in PowerShell. Below I’ll show you a a simple function to create centered headers. All you need to do is adjust the parameter $Width to the desired width.

PowerShell function

Below some examples:

Use PadLeft() and PadRight() to pad (expand) a string at either end, and fill space up with the characters you want. you can now do many related things, i.e. create list of server names with fixed-length numbers:


Accepting Parameters without Quotes

As you can see, the function above works good, but the user needs to quote the string once it contains spaces or other special characters. This can be easily done by using the revised PowerShell function. We use the ValueFromRemainingArguments attribute to allow PowerShell to assign all unbound (extra) arguments to that parameter. We also use distinct data types for parameters so PowerShell knows how to convert ambiguous data. Without a [string] data type, for example, PowerShell would have created a string array from your input values when a string contained spaces.

Below some examples:

However, there is one caveat, any special characters such as parenthesis and quotes are interpreted and can still interfere.

I really like to hear what you have to say about this article:

  • Was this article helpful for you or do you have any questions?
  • Do you have additions, suggestions or any other ideas?
  • Just let me know by leaving a comment below.

Thank you for spending some time at my site and in my blog. I hope you come to visit again soon 😉

About Lex van der Horst 201 Articles

Be the first to comment

Leave a Reply