Question

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")
Was it helpful?

Solution 2

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"

OTHER TIPS

$(Get-Date).addDays(-$(Get-Date).Day).addMonths(-1).ToString("yyyyMMdd")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top