Powershell – How to decipher Powershell syntax for text formatting

formattingpowershelltext;

I found a PowerShell script that I thought I could adapt to my purposes.

It contains this line that formats the output:

$largeSizefiles = get-ChildItem -path $filesLocation -include $Extension -recurse -ErrorAction "SilentlyContinue" | ? { $_.GetType().Name -eq "FileInfo" } | where-Object {$_.Length -gt $fileSize} | sort-Object -property length  | Select-Object Name, @{Name="Size In KB";Expression={ "{0:N0}" -f ($_.Length / 1KB)}},@{Name="LastWriteTime";Expression={$_.LastWriteTime}},@{Name="Path";Expression={$_.directory}} -first $filesLimit

The key part seems to be this:

Select-Object Name, @{Name="Size In KB";Expression={ "{0:N0}" -f ($_.Length / 1KB)}},@{Name="LastWriteTime";Expression={$_.LastWriteTime}},@{Name="Path";Expression={$_.directory}} -first $filesLimit

I have read the ss64.com tutorial on Select-Object, but I don't find anything to explain how the expressions of the form @{…..} are formatting the text.

The ss64.com page on the @ operator shows it in the format of @( … ), with parens, not braces.

The code above results in the following output:

Name          : RPI-Image-1-Copy.img
Size In MB    : 29,477
Path          : D:\VirtualDriveShare
LastWriteTime : 8/18/2015 6:27:51 PM

I'm familiar with a number of programming languages, but this is non-obvious to me, and I haven't found any clear explanation online. Can anyone point me to a good tutorial?

Best Answer

Select-Object can use a hash table of Header/Values for each item. In this example:

Select-Object Name, @{Name="Size In KB";Expression={ "{0:N0}" -f ($_.Length / 1KB)}} ...

the script is selecting Name, then "Name in KB" that is derived from the current pipeline object's Length parameter.

This is further formatted by first dividing it by 1024 then using {0:N0} to display it.

Powershell uses the .Net string format syntax for display - in this case {0:N0} translates into:

// N or n (Number): It represent how many decimal places of zeros to show.
String.Format("{0:N4}", pos);      //”10.0000″

You might want to take a look at Kathy Kam's Format 101 and Format 102 articles:

for further details on string formatting.