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

Thursday, May 03, 2018

Powershell: reveal hidden/truncated data in output

Things to try

1. $FormatEnumerationLimit = –1

2. Select-Object –ExpandProperty <property>

Output will display everything.

https://blogs.technet.microsoft.com/heyscriptingguy/2011/11/20/change-a-powershell-preference-variable-to-reveal-hidden-data/


Share/Bookmark

Powershell: List basic path info for all folders recursively

Had the need to create one big list of all folders in a folder tree. I could get this using Get-Childitem but it broke it down into a nicely formatted output, which is not what I needed.

I wanted just one path per line.

I came up with the following. Initially the output was being truncated, so long paths were truncated with …

This truncate can be removed by setting the following variable to –1

$FormatEnumerationLimit=-1

Not sure why but $FormatEnumerationLimit didnot work, I have to use the ExpandProperty function of the select-object cmdlet.

Get-ChildItem -path \\server\rootfolderpath -Recurse | ?{ $_.PSIsContainer }| Select -ExpandProperty FullName | Format-table FullName > folders.txt


Share/Bookmark