Project maintained by timhaintz Hosted on GitHub Pages — Theme by mattgraham

Save a file with today’s date as part of the file name: Get-Date

Get-Date

Often, when running a regular report, I like to keep the date in the name of the output file. This removes any potential file overwrite issues and is a good visual indicator for the history of the job.

To do this, I use the Get-Date cmdlet.

PowerShell Code Block - Get-Date Default

Get-Date
Monday, May 7, 2018 9:19:08 PM

This isn’t particularly useful to put in a filename.

Luckily for us, Get-Date has a -Format parameter. The -Format parameter can be used to display the date in a number of ways.

PowerShell Code Block - Get-Date -Format

Get-Date -Format yyMMdd
180507

To use it in a file name, I like to save the date in the desired format as a variable and then use it in the filename.

PowerShell Code Block

$dateyyMMdd = Get-Date -Format yyMMdd
Get-Process > $dateyyMMdd-Process.txt

PS C:\Users\azureadmin\test> ls


    Directory: C:\Users\azureadmin\test


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         5/7/2018   9:34 PM          16382 180507-Process.txt

You can use Get-Date -Format in a number of ways. For a list of available format specifiers, see the DateTimeFormatInfo Class

PowerShell Code Block - Get-Date -Format Examples

Get-Date -Format ddMMyy
070518

Get-Date -Format D
Monday, May 7, 2018

Get-Date -Format d
5/7/2018

Get-Date -Format R
Mon, 07 May 2018 21:46:29 GMT

Get-Date -Format u
2018-05-07 21:46:49Z

As you can see, these are just some of the ways you can format the date and time.

Experiment and see which option works best for you.

Thanks, Tim.