Comparing dates with Max date

Welcome Forums General PowerShell Q&A Comparing dates with Max date

Viewing 1 reply thread
  • Author
    Posts
    • #174868
      Participant
      Topics: 1
      Replies: 0
      Points: 17
      Rank: Member

      I have $b and $T. $b is a list with id and dates and $b is the max date. I would like to have all the data in $b which is after the Max Date which is in $b. $b and $T id and dates are changing on a daily basis.

      $b=
      
      audit_id                  modified_at
      
      --------                               -----------
      
      Person1                 04/02/2017 10:59:15
      
      Person2                 04/02/2017 11:43:18
      
      Person3                 10/08/2019 10:42:19
      
      Person4                 04/09/2019 13:34:58
      
      
      
      $T=
      
      31 May 2019 18:06:00
      
      
      Desired Result: -
      
      audit_id                  modified_at
      
      --------                  -----------
      
      Person3                 10/08/2019 10:42:19
      
      Person4                 10/10/2017 13:34:58
      
      

      I have converted the string into Datetime but I am struggling getting the desired result. Here is the code:

      $ServerInstance = Get-AzSqlServer -ResourceGroupName 'X' | where {$_.ServerName -eq 'Y'}
      
      $params = @{
          'Database'       = 'a'
          'ServerInstance' =
          'Username'       = 'John'
          'Password'       = 'Doe'
          'Query'          = 'SELECT MAX(modified_at) AS "MAX_Date" FROM [dbo].[table]'
      }
      
      $a = Invoke-Sqlcmd @params
      $S = $a.MAX
      $T = Get-Date $S
      
      
      $access_token = "Access_Token"
      $URI = "https://iou.api"
      $headers = @{“authorization” = “Bearer $access_token”}
      $result = Invoke-RestMethod -Uri $URI -Headers $headers -ContentType $ContentType |ConvertTo-Json
      $b = $Result|ConvertFrom-Json| Select -ExpandProperty audits
      $Dates = $b.modified_at
      $reportList = @(
          $Dates
      )
      
      foreach ($report in $reportList) {
          Get-Date $report
          If ($report -gt $T) {
              Write-Host $T
          }
      }
      
    • #174979
      Participant
      Topics: 6
      Replies: 108
      Points: 302
      Helping Hand
      Rank: Contributor

      You're never saving the value from "Get-Date $report" so your comparison is actually comparing the string version of $report to a the DateTime object $T. You can do the comparison a couple of ways:

      foreach ($report in $reportList) {
      $repDate = Get-Date $report
      if ($repDate -gt $T) {
      Write-Host $T
      }
      }
      
      # or shortcut it a little
      
      foreach ($report in $reportList) {
      If ($(Get-Date $report) -gt $T) {
      Write-Host $T
      }
      }
      
Viewing 1 reply thread
  • The topic ‘Comparing dates with Max date’ is closed to new replies.