Powershell: Select-Object with additional calculated difference value

Posted by David.Chu.ca on Stack Overflow See other posts from Stack Overflow or by David.Chu.ca
Published on 2010-04-30T17:38:31Z Indexed on 2010/04/30 17:47 UTC
Read the original article Hit count: 608

Filed under:

Let me explain my question. I have a daily report about one PC's free space as in text file (sp.txt) like:

DateTime       FreeSpace(MB)
-----          -------------
03/01/2010     100.43


DateTime       FreeSpace(MB)
-----          -------------
03/02/2010     98.31

 ....

Then I need to use this file as input to generate a report with difference of free space between dates:

DateTime       FreeSpace(MB)  Change
-----          -------------  ------
03/01/2010     100.43
03/02/2010     98.31           2.12
 ....

Here are some codes I have to get above result without the additional "Change" calculation:

Get-Content "C:\report\sp.txt" `
| where {$_.trim().length -gt 0 -and -not ($_ -like "Date*") -and -not ($_ -like "---*")} `
| Select-Object @{Name='DateTime'; expression={[DateTime]::Parse($_.SubString(0, 10).Trim())}}, `
    @{Name='FreeSpace(MB)'; expression={$_.SubString(12, 12).Trim()}}, `
| Sort-Object DateTime `
| Select-Object DateTime, 'FreeSpace(MB)' |ft -AutoSize # how to add additional column Change to this Select-Object?

My understanding is that Select-Object will return a collection of objects. Here I create this collection from an input text file(parse each line into parts: datetime and freespace(MB)).

In order to calculate the difference between dates, I guess that I need to add additional calculated value to the result of the last Select-Object, or pipe the result to another Select-Object with the calculation as additional property or column. In order to do it, I need to get the previous row's FreeSpace value. Not sure if it is possible and how?

© Stack Overflow or respective owner

Related posts about powershell