PowerShell Tip of the Week: Get name of a month and number of days

get-date

Recently I was working on a new report for entire environment. I had to calculate servers total uptime and downtime in previous month. I prepared script for that and one of the tasks was to check what was previous month name and number of days.

Name of a month

Concept of uptime report was that script will gather start/stop/crash information from eventlog and calculate time between of those events. It will run every 1st day of a month and check events from previous month on all online servers. Final results will be send to email. Part of the code was about getting information like name of the month, number of days etc. Based on that data script will set time start and end time for querying events.

This simple script is mainly based on Get-Date command. Below you can find how to get last month name and number of days:

$CurrentDate = Get-Date
$LastMonth = (($CurrentDate).AddMonths(-1)).ToUniversalTime().Month
$LastMonthYear = (($CurrentDate).AddMonths(-1)).ToUniversalTime().Year
$LastMonthName = $LastMonth | %{(Get-Culture).DateTimeFormat.GetMonthName($_)}
$LastMonthDays = [DateTime]::DaysInMonth($LastMonthYear, $LastMonth)
name of a month

Now, we can use this code and calculate start and end of the month. This can be useful for example in getting event logs in specific time frame:

$StartOfPrevMonth = Get-Date -Month $LastMonth -Year $LastMonthYear -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
$EndOfPrevMonth = ($StartOfPrevMonth).AddMonths(1).AddTicks(-1)
name of a month

Both variables can be used as Get-WinEvent paramters, starttime and endtime:

$CurrentDate = Get-Date
$LastMonth = (($CurrentDate).AddMonths(-1)).ToUniversalTime().Month
$LastMonthYear = (($CurrentDate).AddMonths(-1)).ToUniversalTime().Year
$LastMonthName = $LastMonth | %{(Get-Culture).DateTimeFormat.GetMonthName($_)}
$LastMonthDays = [DateTime]::DaysInMonth($LastMonthYear, $LastMonth)
$StartOfPrevMonth = Get-Date -Month $LastMonth -Year $LastMonthYear -Day 1 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
$EndOfPrevMonth = ($StartOfPrevMonth).AddMonths(1).AddTicks(-1)

"Scan time frame: $StartOfPrevMonth - $EndOfPrevMonth"

Get-WinEvent -FilterHashTable @{LogName='System'; ID="6005","6006","6008"; StartTime=$StartOfPrevMonth;EndTime=$EndOfPrevMonth}
name of a month

I hope this was informative for you 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.