PowerShell Date Functions

Save

Windows PowerShell is a shell and scripting language that is part of the .NET Framework that uses cmdlet -- "command-lets" -- commands or functions to perform operations. PowerShell has one main date function called "Get-Date" that returns the current date and time. Get-Date has several methods and properties that let you change the date format or extract portions of the date as needed in your script.

Date Formatting

  • By default, Get-Date returns a long date pattern. For example, calling it may have "Friday, January 6, 2012 10:32:12 AM" returned. You may want another pattern. PowerShell can use Windows' .NET Framework to access other formats, including short dates, full dates or general types to display the date differently, each format specified by a unique character, including "d" for a short date, "D" for a long date or "M" for a month and day pattern. Typing "$date = Get-Date -format d" in your script returns a short date pattern with a "MM/DD/YYYY" format.

Properties

  • Sometimes you don't need the entire date in your script. You may only need the day and the month, or just the year. After calling Get-Date and saving the result to a variable, you can extract portions of the date by accessing Get-Date's properties. For example, typing "$date.Day" returns the day, $date.Month" returns the month, and so on for the year, hour, minute and second properties. You can also return just one property when calling Get-Date, for example, by typing "$month = (Get.Date).Month" in your script.

Methods

  • Similar to Get-Date's properties, the "ToShortDateString" method returns a portion of a full date-time value. After calling Get-Date, you can extract just the date portion by typing "$date.ToShortDateString()" in your script, which returns the day, month and year with a "MM/DD/YYYY" format; note the empty brackets at the end of the method call. Likewise, the "DayOfWeek" and "DayOfYear" methods work the same as "ToShortDateString," except they return the values indicated by their names -- they also don't require brackets.

Get-Date Arithmetic

  • If you want to make a calendar or simply want to know what day of the week it will be 500 days from now, you can use Get-Date's arithmetic functions to incorporate this functionality into your script. For example, typing "$date.AddDays(500) will add 500 days to the value saved in the $date variable. Likewise, ""$date.AddDays(-500)" will subtract 500 days." You can use additional methods including "AddYears," "AddMonths," "AddHours," "AddMinutes" and "AddSeconds."

References

Promoted By Zergnet

Comments

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!