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

Don't miss the next post!

SQL UNION vs UNION ALL

UNION is one of the four basic ‘set operators’ in SQL. The UNION operator is used to combine the results of two or more SELECT Statement queries into a single result-set, excluding duplicate values.

SQLite
SQL UNION
SQL UNION ALL
SQL Operator
SQL Set Operator