Search code examples
powershell

Get the last day of a month on powershell


I'm trying to put in a .txt file the first day and the last day of the months using PowerShell.

In the exemple below i was trying to get the first and the last day of July, but i'm just getting the first day. The second line of the script isn't working.

@PowerShell "(Get-Date).AddMonths(1).ToString('01/MM/yyyy')" >>dates.txt 
$LastDayInMonthString = "$($(get-date).AddMonths(1).ToString("dd/mm/yyy"))$LastDayInMonth" >>dates.txt

Someone can say me what is wrong?

I wanted a .txt file like it: 01/07/2018, 31/07/2018.
The first line write the first day of next month,
and second line write the last day of that month.


Solution

  • Edit removed the for only date unneccessary time adjustments

    In PowerShell to get the first day and last of next month

    $CIGB = New-Object System.Globalization.CultureInfo('en-GB')
    '{0}, {1}' -f (Get-Date -Day 1).AddMonths(1).ToString('d',$CIGB),
      (Get-Date -Day 1).AddMonths(2).AddDays(-1).ToString('d',$CIGB)|sc dates.txt
    

    The $CIGB is neccessary for me because my local date separator overrides the /
    If your short date format 'd' returns dd/MM/yyyy the first line and the ,$CIGB can be removed.

    01/07/2018, 31/07/2018
    

    This can be wrapped in a single (albeit quite long) line.

    powershell -nop -c "$CIGB=New-Object System.Globalization.CultureInfo('en-GB');'{0}, {1}' -f (Get-Date -Day 1).AddMonths(1).ToString('d',$CIGB),(Get-Date -Day 1).AddMonths(2).AddDays(-1).ToString('d',$CIGB)">>dates.txt
    

    > type dates.txt
    01/07/2018, 31/07/2018