PDQ.com mobilePDQ.com desktop
Support

PowerShell:Get-Date Cmdlet

Kris PowellKris Powell
·

Today, I’d like to make use of an awesome PowerShell cmdlet, Get-Date. Get-Date as the name implies, gets the current date and time and use the results for other cmdlets. Get-Date by itself will return the current date.

PowerShell Get-Date Cmdlet 1

We can manipulate this result a handful of ways to make the date into a format that’s more useful to our needs.

We can use -Format to view the date any just about any date format that we can imagine.

PowerShell Get-Date Cmdlet 2

Here is a great link for which format patterns you can use – http://ss64.com/ps/syntax-dateformats.html

In addition to formatting the date to whatever format suits you best, there are also methods you can use to manipulate the date itself (not just the formatting).

In this example, we can see what day it will be a week from now:

PowerShell Get-Date Cmdlet 3

Here’s a quick list of methods you can use to modify Get-Date:

  • AddDays

  • AddHours

  • AddMilliseconds

  • AddMinutes

  • AddMonths

  • AddSeconds

  • AddTicks

  • AddYears

We can make use of Get-Date and these methods in our scripts to do fancy things like finding all files that have been created within the last 30 days. We can even take that result and process it to remove the files that are found.

#############################################################################
# Find files older than 30 days
#############################################################################

$time = (Get-Date).AddDays(-30)
$path = "C:\temp"

Get-ChildItem -Path $path -Recurse -Force | `
Where-Object {$_.LastWriteTime -lt $time }

#############################################################################
# Find files older than 30 days and DELETE
# Please excercise caution. There is no undo to this action
#############################################################################

$time = (Get-Date).AddDays(-30)
$path = "C:\temp"

Get-ChildItem -Path $path -Recurse -Force | `
Where-Object {$_.LastWriteTime -lt $time } | `
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

Don't miss the next post!

How PowerShell can calculate your retirement

How PowerShell can track 401K growth

In this blog, I use PowerShell to focus and build a 401k calculator because its tax advantages make it ideal to build your retirement nest egg.

PowerShell