PowerShell for Windows Admins

Nov 19 2011   5:46AM GMT

Using calculated fields in subsequent processing

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: