weatherdoc
weatherdoc

Reputation: 25

How can I use comparison operators in PowerShell to compare values in cells

I would like to compare the values of adjacent cells in two columns (wind Speed and Gust) in a CSV file and if the value of the cell in the Gust column is less than the value of the adjacent cell in the Speed column, replace the value of the cell in the Gust column with that of the Speed. For example, my file might look like:

Time    Speed   Gust
22:06   6.1 12.7
22:07   6.3 5.2
22:08   7.2 6.9
22:09   11.1    10.3
22:10   5.9 6.9
22:11   6   16.1
22:12   6.3 12.7

For the times of 22:07, 22:08, and 22:09, the wind Gust is less than the wind Speed and they are the only Gusts that should be changed. However, for the times of 22:06, 22:11 and 22:12 in which the gust is greater than 10, those Gusts are changed to be equal to the Speed resulting in:

Time    Speed   Gust
22:05   6.1 8.1
22:06   6.1 6.1
22:07   6.3 6.3
22:08   7.2 7.2
22:09   11.1    11.1
22:10   5.9 6.9
22:11   6   6
22:12   6.3 6.3

My code is:

$data = Import-Csv ‘C:\customfiles\speed.csv’

foreach ($datum in $data) {
    if ($datum.Gust -le $datum.Speed) {$datum.Gust = $datum.Speed}
    }
 
$data | Export-Csv 'C:\customfiles\speed-new.csv' -NoTypeInformation

I would expect that using the -le comparison operator would result in only values of Gusts less than or equal to the Speed being changed to match the speed, but if the Gust is greater than 10, the code identifies that cell as less than or equal to the Speed, even if the Gust is greater than the Speed, and then it changes the correct Gust to that of the Speed. Is there a different way to use the comparison operator to avoid this issue?

Upvotes: 0

Views: 249

Answers (1)

vasja
vasja

Reputation: 4792

The type of objects you are comparing is string, so you're getting results based on alphabetic order. You need to convert it into some numeric type, e.g. decimal:

if ([decimal]$datum.Gust -le [decimal]$datum.Speed) {$datum.Gust = $datum.Speed}

Upvotes: 1

Related Questions