title: Powershell HowTo get last day of 2 month ago
body: <p>I've a script scheduled every 4th and 14th day of month.</p>
  
  <p>when script starts on 4th, I need to get the last day of the previous month (easy, $a.AddDays(-5))</p>
  
  <p>when script starts on 14th, I need to get the last day of 2 month before.</p>
  
  <p>for example:</p>
  
  <pre><code> 14 april.
  
   I want to get:28 february 2013
  </code></pre>
  
  <p>how is it possible?
  also I want to get the date in format yyyymmdd</p>
  
  <p>UDPDATE:</p>
  
  <p>Is it possible that your solution doesn't work well with the change of the year? </p>
  
  <p>if I'm in january, $(get-date).month -1 results 0. so I did this: </p>
  
  <pre><code> $datenow = Get-date
   if $datenow.day -eq 14
   $datenow.AddDays(-14)
  </code></pre>
  
  <p>then I calculate </p>
  
  <pre><code> $LastDayInMonth = [System.DateTime]::DaysInMonth($(Get-date).Year, $(Get-date.Month))
   $datenow.AddDays(-$LastDayInMonth)
   $datestring = $datenow.ToString("yyyyMMdd")
  </code></pre>