Powershell HowTo get last day of 2 month ago
Asked Answered
I

2

5

I've a script scheduled every 4th and 14th day of month.

when script starts on 4th, I need to get the last day of the previous month (easy, $a.AddDays(-5))

when script starts on 14th, I need to get the last day of 2 month before.

for example:

 14 april.

 I want to get:28 february 2013

how is it possible? also I want to get the date in format yyyymmdd

UDPDATE:

Is it possible that your solution doesn't work well with the change of the year?

if I'm in january, $(get-date).month -1 results 0. so I did this:

 $datenow = Get-date
 if $datenow.day -eq 14
 $datenow.AddDays(-14)

then I calculate

 $LastDayInMonth = [System.DateTime]::DaysInMonth($(Get-date).Year, $(Get-date.Month))
 $datenow.AddDays(-$LastDayInMonth)
 $datestring = $datenow.ToString("yyyyMMdd")
Illnatured answered 30/4, 2013 at 20:2 Comment(0)
B
6

To get the date in a string:

$(get-date).Date.ToString("yyyyMMdd")

For getting the last day of two months prior:

if($(get-date).Day -eq 14){
    $LastDayInMonth = [System.DateTime]::DaysInMonth($(get-date).Year, $($(get-date).Month - 2))

}

Update

The line

$LastDayInMonth = [System.DateTime]::DaysInMonth($(get-date).Year, $($(get-date).Month - 2))

Uses the static method DaysInMonth in the System.DateTime class to get the days in the month of the month that is passed to it. It's documentation is here. It takes as input two parameters, the month as an integer, and the year as an integer as well.

In our case, we want 2 months before this month, so for the month parameter we pass in

$(get-date).month - 2

And that is surrounded in a parenthesis to make sure powershell does the calculation and then pass the result of the calculation. get-date is a powershell cmdlet that gives the current date and time as a .NET dateTime object, so we have all the properties and methods at our disposal.

The whole

[System.DateTime]::DaysInMonth()

is just the way of calling static methods in powershell.


Update 2

Once you get the last day in the month, you can concatenate the string by:

$LastDayInMonthString = "$($(get-date).AddMonths(-2).ToString("yyyyMM"))$LastDayInMonth"
Bogeyman answered 30/4, 2013 at 20:18 Comment(2)
can you explain that line?Illnatured
another doubt: after I got the value of $LastDayInMonth (i.e. 28) I want to get something like "20130228". is it possible? I know to use method .ToString("yyyyMMdd") but I don't know how to concatenate those numbersIllnatured
W
3
$(Get-Date).addDays(-$(Get-Date).Day).addMonths(-1).ToString("yyyyMMdd")
Wallache answered 17/6, 2014 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.