Search code examples
powershelldate-arithmetic

How to mathematically find the nearest odd month below


PowerShell returns the current month with:

(Get-Date).Month

But I need to know the nearest odd month below.

If each month is represented by the matching number inside a year:

 1 →  1
 2 →  1
 3 →  3
 4 →  3
 5 →  5
 6 →  5
 7 →  7
 8 →  7
 9 →  9
10 →  9
11 → 11
12 → 11

Solution

  • Check if divisible by 2:

    $m = (Get-Date).Month
    if ($m % 2 -eq 0) { 
      $m -= 1 
    } 
    
    Write-Host $m
    

    Proof:

    1..12 | % { Write-Host -nonewline "$_ ==> " ; if ($_ % 2 -eq 0 ) { $_ -= 1} ; Write-Host $_ }