Using calculated fields in subsequent processing
A calculated field can be created in Select-Object or Format-Table. When you use Format-Table processing effectively stops, the pipeline terminates and you are dumping the results to screen. The objects produced by Format-Table are not meant for further processing.
If you use Select-Object to create the calculated field the results are an object on the pipeline that can be used for further processing. As a simple example consider
Get-ChildItem -Path c:\windows
This produces the file sizes in bytes. Lets say that we want the sizes in KB
Get-ChildItem -Path c:\windows |
where {!$_.PSIsContainer} |
select Name, @{Name="Size(KB)"; Expression={[math]::round($($_.Length/ 1kb), 2)}}|
Format-Table -AutoSize
OK this is good. I've used the math rounding method as it leaves me with a number rather than a string
No we want to sort of the Size(KB) field so the biggest file is shown first
You might think that
Get-ChildItem -Path c:\windows |
where {!$_.PSIsContainer} |
select Name, @{Name="Size(KB)"; Expression={[math]::round($($_.Length/ 1kb), 2)}}|
sort Size(KB) -Descending |
Format-Table -AutoSize
would work. But we get an error
The term 'KB' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:4 char:13
+ sort Size(KB <<<< ) -Descending |
+ CategoryInfo : ObjectNotFound: (KB:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
When we have a property name that isn't a single simple word we need to put it in quotes like this
Get-ChildItem -Path c:\windows |
where {!$_.PSIsContainer} |
select Name, @{Name="Size(KB)"; Expression={[math]::round($($_.Length/ 1kb), 2)}}|
sort -Property "Size(KB)" -Descending |
Format-Table -AutoSize
To work with properties that we create in calculated fields where their names aren't simple - wrap the name in quotes