Search This Blog

Monday, May 07, 2018

Powershell: Format Fixed Width String (-f format operator)

Had to build a table in a text format of a predetermined width. What I found is that the –f operator can assist with building this

I had a variable that I stored the text output in, and then appened the results to it.

Add table header to string variable

$StringOutput += "{0,-80}{1,10}{2,25}" -f 'Filename','Size (KB)','Date';

Then loop through results

foreach (item in list)

{

$sqlStringOutput += "{0,-80}" -f $item.Name + "{0,10}" -f ("{0:n2}" -f ($item.Length/1kb)) + "{0,25}" -f ("{0:yyyy-MM-dd HH:mm:ss}" -f ([datetime]::ParseExact($item.LastWriteTime,'MM/dd/yyyy HH:mm:ss',$null))) + $htmlbr;

}

Output

Filename                                                                         Size (KB)                     Date

filename1.bak                                                                         0.50      2018-04-22 22:37:40
filename2.bak                                                                         0.50      2018-04-23 22:39:35

So I have used different ways to build the string using formatting.

1. "{0,-80}{1,10}{2,25}"  - this is one format string, the first number 0,1,2 are the indexes of the following strings. the –80,10,25 are how wide the end string is (with padding), the – number means align left, positive align right.

2. I used multiple format strings then concatenate them together, I just found it easier to read (due to nested format strings on the numbers and dates.

References

https://blogs.technet.microsoft.com/heyscriptingguy/2013/03/11/understanding-powershell-and-basic-string-formatting/

https://ss64.com/ps/syntax-f-operator.html


Share/Bookmark

No comments:

Post a Comment