I have the following selfdriving.log
file for a self-driving car:
2021.04.01., 13:14:30:78, 78, 110, 110
2021.04.01., 13:14:30:99, 79, 111, 111
2021.04.01., 13:14:31:50, 80, 111, 119
2021.04.01., 13:14:59:87, 87, 118, 117
2021.04.01., 13:16:59:87, 86, 116, 119
2021.04.01., 13:17:22:32, 75, 117, 115
2021.04.01., 13:18:50:65, 75, 96, 109
2021.04.01., 13:18:55:00, 20, 30, 57
Where in each line there's the date, the time, the speed of the vehicle and the measured distance before and after the vehicle. I have to return the date and time when the distance before the vehicle is smaller than the argument given in the terminal.
So for ./logReading.ps1 100
it should return:
2021.04.01. 13:18:50:65
2021.04.01. 13:18:55:00
Right now, I have this code:
$k=$args[0]
write-host $k
get-content .\selfdriving.log | foreach{
$date,$time,$speed,$before,$after = $_.split(", ").trim()
if($before -gt $k){
write-host $date, $time
}
}
But for some reason, no matter how I write the inequality in my if
statement, I always get the wrong values for logReading.ps1 100
.
CodePudding user response:
$before
is of type string, Hence you need to cast $before
to int
prior to the comparison.
> "96" -gt 100
True
> [int]"96" -gt 100
False
So your final if
statement should look like this.
if([int]$before -gt $k){
Write-Host $date, $time
}
Alternatively you can also change the type during the unpacking statement.
$date,$time,$speed,[int]$before,$after = $_.split(", ").trim()