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.

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.

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:

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

This blog post is part of a series on PowerShell:

Ready to put the PowerShell Scanner through its paces?

Take our 14-day Free Trial. Feel the power of the PowerShell scanner.
Start a Trial

Don't miss the next post!

(CVE-2020-1472) 'ZeroLogon' Vulnerability

The Zerologon Vulnerability Allows Attackers To Completely Take Over Your Domain Controller Without Credentials.

PDQ.com
© 2020 PDQ.com Corporation

Products

  • PDQ Deploy
  • PDQ Inventory
  • PDQ Link
  • Enterprise SL
  • Pricing
  • Downloads
  • Licensing
  • Buy