Operator '-gt' is not working in this PowerShell

前端 未结 2 1013
傲寒
傲寒 2021-01-21 07:55

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.

相关标签:
2条回答
  • 2021-01-21 08:12

    -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
    
    0 讨论(0)
  • 2021-01-21 08:13

    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
    
    0 讨论(0)
提交回复
热议问题