Search code examples
powershelldatetimepowershell-4.0getdate

How to check if a user passed date is Wednesday using PowerShell?


I have an use case where user passes a date from the past. But I need to check if it's a Wednesday. If not, I want to be able to set it to next Wednesday 5 AM. Can somebody please tell me what would be best approach to go about this using PS?

Thanks.


Solution

  • Fortunately [datetime] structs have a DayOfWeek property we can use to check that!

    Simply advance the date by 1 day at a time until you reach Wednesday:

    function Get-UpcomingWednesdayAt5
    {
      param(
        [datetime]$Date
      )
    
      while($Date.DayOfWeek -ne [System.DayOfWeek]::Wednesday){
        # advance 1 day at a time until its wednesday
        $Date = $Date.AddDays(1)
      }
    
      # Create new [datetime] object with same Date but Time set to 5AM
      return Get-Date -Date $Date -Hour 5 
    }