Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator '-gt' is not working in this PowerShell

Tags:

powershell

I have a PowerShell script which reads a CSV file and filters out data as per my requirement, but the catch is that it ONLY works on my Windows 8.1 system and nowhere else. The -gt operator to be precise, the script runs on other systems if I change the -gt to lt, le, etc.

Below is the script.

$date1 = Date ("{0:MM/dd/yyyy}" -f (get-date).AddDays(-1)) -format G

echo $date1

Import-Csv C:\avaya\2014.04.csv | Where-Object { $_.Party1Name -eq "User_Name" -and $_.'Call Start' -gt ( $date1 ) } | Export-Csv -Path "result.csv" -NoTypeInformation
like image 350
gkanu7 Avatar asked Feb 03 '26 19:02

gkanu7


2 Answers

-gt is working as it should. The problem is that you're trying to compare string-values with -gt. To compare dates, they need to be DateTime-objects. When you import a CSV file, all values are imported as strings. You need to convert the date back to a DateTime-object. Ex:

$date1=(get-date).AddDays(-1)

echo $date1

Import-Csv C:\avaya\2014.04.csv | Where-Object { $_.Party1Name -eq "User_Name" -and ($_.'Call Start' -as [datetime]) -gt $date1 } | Export-Csv -Path "result.csv" -NoTypeInformation
like image 80
Frode F. Avatar answered Feb 05 '26 09:02

Frode F.


It's not working the way you expect because what you're doing is a string comparison, not a date comparison.

What you have in your CSV file is a date string. When using comparison operators, PowerShell will base the type of comparison on the object type on the left hand side, and if necessary coerce the right-hand side to the same type in order to perform the operation. Start with a datetime object, and put it on the left hand side, and PowerShell will coerce the string on the right-hand sided to a datetime for you:

$date1 = (get-date).AddDays(-1)

echo $date1

Import-Csv C:\avaya\2014.04.csv |
 Where-Object { $_.Party1Name -eq "User_Name" -and $date1 -lt $_.'Call Start' } |
 Export-Csv -Path "result.csv" -NoTypeInformation
like image 32
mjolinor Avatar answered Feb 05 '26 08:02

mjolinor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!