How to decipher Powershell syntax for text formatting?

Solution 1:

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:

  • https://blogs.msdn.microsoft.com/kathykam/2006/03/29/net-format-string-101/

  • https://blogs.msdn.microsoft.com/kathykam/2006/09/29/net-format-string-102-datetime-format-string/

for further details on string formatting.

Solution 2:

What you're missing is that @{...} indicates a hashtable array, which are composed of key-value pairs.

As pointed out in the comments, there's a Technet article on this very thing. In your example, what's happening is the name/title is being assigned to the key in the hashtable, and a variable with a formatting expression is being assigned to the value in the hashtable.

Hashtables in PowerShell are fairly straightforward, but in case it's helpful, ss64's page is here, and Technet has a tutorial page as well.

Solution 3:

I agree with all other answers, the hash-table being a calculated property in this case. I find these one liners wonderful, but they could be presented in a far better way. Technical still a one-liner but readability on a different scale.

$largeSizefiles = get-ChildItem `
    -path $filesLocation `
    -include $Extension `
    -recurse `
    -ErrorAction "SilentlyContinue" | 
  Where-object { ($_.GetType().Name -eq "FileInfo") `
            -and ($_.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

If PoSh expects a continuation (after a , or a |) you can simply insert a newline or of course after the line continuation char the backtic ` .