Working with dates in PowerShell: Tips and tricks

When I write PowerShell scripts, I have often found that I need to reference the date. For example, I have occasionally written scripts that pull Windows event logs from a particular date or scripts that archive aging data based on the date when a file was created. Those are just a couple of examples of how the date may need to be referenced within a PowerShell script. In this article, I want to show you a few tricks for working with dates in PowerShell.

Retrieving the date

It is simple to make PowerShell display the current date. To do so, just enter the Get-Date cmdlet. If you need to display the date in a certain way, then PowerShell offers a number of different options for doing so. The simplest method is to use a display hint. The DisplayHint parameter can be set to Date, Time, or DateTime. The image below shows how the basic Get-Date cmdlet works, and a few examples of using the DisplayHint parameter.

dates in PowerShell

If you need a bit more control over the output, you can use the Format parameter or the UFormat parameter. The Format parameter is mostly used when you need to put the date into a certain format for the purpose of making a comparison. We won’t be using the Format parameter in this article, but it is still a good idea to be aware of its existence.

The UFormat parameter is used more for display purposes. It allows you to arrange the various elements that make up the date and time in a way of your choosing. All you have to do is to append various formatting characters to the UFormat parameter. The parameters that you can use include:

%M — Month (as a number)
%D — Date
%Y — Year
%A — The day of the week
%Z — The time zone, expressed as an offset from UTC or Zulu time. For example, -5 is Eastern Time in the United States.

You can see an example below of how the UFormat parameter works.

dates in PowerShell
There are two things that are worth paying attention to in the image above. First, you will notice that everything following the UFormat parameter is enclosed in quotation marks. This is because I am not just specifying formatting characters, I can also use text. In the figure, I used a mixture of text and formatting characters.

The other thing to notice is that even though I live on the East Coast of the United States, which normally has a time zone offset of -5, the output in the figure above shows the offset as -4. This is because it is daylight saving time. But wouldn’t it be nice to be able to verify that? We can actually. Here is how it’s done:


$A=Get-Date
$A.IsDaylightSavingTime()


As you can see in the image below, PowerShell shows a value of True, indicating that it is indeed daylight savings time.

What about the day of the year?

We can also use PowerShell to tell us what day of the year it is. Here is how that works:


$A=Get-Date
$A.DayOfYear


If you really want to make things interesting, though, you can specify a date to find out what day of the year that date falls on. The date that you specify can be past or future. Here is an example:


Get-Date -Year 2018 -Month 8 -Daye 22).DayOfYear


You can see a couple of examples in the image below.
dates in PowerShell

Making date comparisons

As I said earlier, it is possible to use PowerShell to make date comparisons. Although you can use the -Format parameter to put the date into a specific format prior to comparing it to another value, doing so is not always necessary. For example, comparing file write dates does not require the use of any special formatting.

Let’s suppose for a moment that you wanted to compare the last write time for a particular file to a date and time of your choosing to see if the file was written to more recently than the specified date.

In a situation like this, the first thing that we have to do is to map our target date to a variable. For the sake of demonstration, I will map January 2, 2017 (which is a random date), to the variable A$. I will then map a particular file to a variable, which I will call X$. It will then be possible to make comparisons between the two. So here are the commands that I am going to use:


$A = (Get-Date -Year 2017 -Month 01 -Day 02)
$A
$X = Get-ChildItem Readme.txt
$X.LastWriteTime
$X.LastWriteTime -GT $A


The first line of code maps the $A variable to January 2, 2017. The next line simply verifies that the variable contains the desired date. The third line of code maps the $X variable to a file named ReadMe.txt. The fourth line displays the last write time for the file. The final line of code makes a comparison between the two dates. It will show True is the file was written more recently than January 2, 2017. Otherwise, it will show a value of False. The screen capture below shows this in action. You will also notice that I have added another line to check to see if the file’s last write time is older than (-LT) January 2, 2017. Doing two separate comparisons makes it possible to see that the comparison really is doing what it is supposed to do.
dates in PowerShell

Dates in PowerShell: More to learn

PowerShell actually allows you to do far more with regard to date formatting and comparisons than what I have talked about in this article. If you would like to learn more about using dates in PowerShell, a good place to start is Microsoft’s documentation for the Get-Date cmdlet.

About The Author

10 thoughts on “Working with dates in PowerShell: Tips and tricks”

    1. I don’t quite understand what it is that you need. Can you give me an example of what you are trying to do?

  1. Wow, Brien, this is pretty timely.

    Not sorry for the bad pun, but this is exactly what I need right now. I’m actually looking to get the name of the last month as a string. Any idea on how to do that?

    1. If nothing else, you could set up some If-Then statements to create text strings based on a month value.

  2. I’m not exactly PowerShell proficient and I found the script below and slightly modified it.

    I need to get today’s date and then pass it into another variable but I’m getting errors and I’m not sure how to get past them. (The “Unzipped” folder is created in a preceding PowerShell script.)

    I works when I give it a static date, instead of “$today”, but won’t work with the variable for the cmdlet “Get-Date”.
    :

    $today = Get-Date -format “yyyyMMdd”
    PARAM (
    [string] $ZipFilesPath = “\\fpserver\dir1\dir2\dir3\dir4\$today\*.zip”,
    [string] $UnzipPath = “\fpserver\dir1\dir2\dir3\dir4\$today\\Unzipped”
    )

    $Shell = New-Object -com Shell.Application
    $Location = $Shell.NameSpace($UnzipPath)

    $ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP

    $progress = 1
    foreach ($ZipFile in $ZipFiles) {
    Write-Progress -Activity “Unzipping to $($UnzipPath)” -PercentComplete (($progress / ($ZipFiles.Count + 1)) * 100) -CurrentOperation $ZipFile.FullName -Status “File $($Progress) of $($ZipFiles.Count)”
    $ZipFolder = $Shell.NameSpace($ZipFile.fullname)

    $Location.Copyhere($ZipFolder.items(), 1040) # 1040 – No msgboxes to the user – http://msdn.microsoft.com/en-us/library/bb787866%28VS.85%29.aspx
    $progress++
    }

  3. Hi, I have the below PS command to extract the LastAccessTime and LastWriteTime. Now I want to add another variable which can provide subtraction of these two times. Please help. Thanks
    Get-ChildItem “C:\Users\2215190\Downloads” -Recurse | Select-Object FullName, LastAccessTime, LastWriteTime

  4. Get-ChildItem “C:\Users\2215190\Downloads” -Recurse | Select-Object FullName, LastAccessTime, LastWriteTime
    Hi, I have the above PS command to extract the LastAccessTime and LastWriteTime. Now I want to add another variable which can provide subtraction of these two times. Please help. Thanks

  5. We have in our scipt a date that is static so we have to change just the year date.

    I’d like it to where we can make the year current by append a static month and date.

    Example:

    $startQ1date = (Get-Date 2019-2-01).toString(“yyyy-M-dd”)
    $startQ2date = (Get-Date 2019-5-01).toString(“yyyy-M-dd”)
    $startQ3date = (Get-Date 2019-8-01).toString(“yyyy-M-dd”)
    $startAnnualdate = (Get-Date 2019-12-01).toString(“yyyy-M-dd”)

    But I’m not as PowerShell efficient, but I was curious if there was a way to automatically make 2019 the current year but makes the M-dd static. So 2019 would change to current year 2021 but month is 12 and day is 01. This way, we’d never have to remember which script it is that won’t run because of old dates in set I the script.

    1. I don’t usually do this, but I wrote an article explaining how to do what it is that you are trying to do. Keep an eye on the site!

Leave a Comment

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Scroll to Top