135

I have a path in a string,

C:\temp\mybackup.zip

I would like insert a timestamp in that script, for example,

C:\temp\mybackup 2009-12-23.zip

Is there an easy way to do this in PowerShell?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Chris Jones
  • 2,630
  • 2
  • 21
  • 34

9 Answers9

260

You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:

"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"

And if you are getting the path from somewhere else - already as a string:

$dirName  = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext      = [io.path]::GetExtension($path)
$newPath  = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"

And if the path happens to be coming from the output of Get-ChildItem:

Get-ChildItem *.zip | Foreach {
  "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • 6
    Argh. `get-date -f yyyy-MM-dd` made me stop for a moment before realizing that it's *not* the `-f` *operator* but the short form for the `-Format` *parameter*. It looked rather out of place, somehow :-) – Joey Dec 24 '09 at 00:11
  • 1
    and if I want the time as well? – John Demetriou Apr 11 '16 at 05:36
  • 1
    @JohnDemetriou see https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx – Keith Hill Apr 12 '16 at 02:19
  • 4
    I use this for timestamped filenames: $timeStr = get-date -f 'yyyy-MM-dd-HHmmss' Maybe with out seconds deparnting on the situation. Note that a colon can't be used in a filename. Can use a dot or dash if you want to separate time components. – jim birch Dec 01 '20 at 22:32
24

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\tempFile.zip";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Hazel
  • 3,232
  • 2
  • 20
  • 20
22

I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:

wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx

The magic code is just this part:

$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
mwfearnley
  • 3,303
  • 2
  • 34
  • 35
Ryker Abel
  • 599
  • 5
  • 4
  • 1
    `hh` is 12-hour time, without `tt` it is not useful. Using `HH` will give you 24-hour time. I'd recommend either `hhmmsstt` or `HHmmss` – Josh Brown Aug 09 '19 at 12:59
  • 1
    @JoshBrown I changed `hh` to `HH` above. I think that's what most people will want. – mwfearnley Apr 09 '20 at 10:32
6

Thanks for the above script. One little modification to add in the file ending correctly. Try this ...

$filenameFormat = "MyFileName" + " " + (Get-Date -Format "yyyy-MM-dd") **+ ".txt"**

Rename-Item -Path "C:\temp\MyFileName.txt" -NewName $filenameFormat
wonea
  • 4,783
  • 17
  • 86
  • 139
2

If you have the path on a variable ($pathfile) use this concrete line to get the TimeStamped Path:

(extracted from here: https://powershellexamples.com/home/Article/10/file-management-add-timestamp-to-file-name)

$pathFile = "C:\ProgramData\MyApp\file.txt"
$pathFileTimestamp = [System.IO.Path]::GetDirectoryName($pathFile) + "\" + `
        [System.IO.Path]::GetFileNameWithoutExtension($pathFile) + "_" + `
        (get-date -format yyyyMMdd_HHmmss) + ([System.IO.Path]::GetExtension($pathFile))


Write-Host "Path+File: $pathFile"
Write-Host "Path+File with Timestamp: $pathFileTimestamp"

Above will return:

PS C:\> Path+File: C:\ProgramData\MyApp\file.txt
        Path+File with Timestamp: C:\ProgramData\MyApp\file_20210328_022045.txt
CContreras
  • 21
  • 2
1

Use:

$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Will Webb
  • 795
  • 6
  • 20
0

Another approach for renaming.

Set-Location C:\Folder_containing_zipfiles
Get-ChildItem -File | ForEach-Object {  Rename-Item -Path $_.FullName -NewName  
 $_.Name.Replace('.zip',"_$(get-date -Format yyyy_MM_dd_hh_mm_ss).zip") }
Venkataraman R
  • 12,181
  • 2
  • 31
  • 58
0

use variable to rename existing file

Get-Content -Path '${{vars.LOG_PATH}}\eventMapper.log'
$filenameFormat = 'eventMapper-' + (Get-Date -Format 'yyyy-mm-dd-hh-mm') + '.log'
Rename-Item -Path '${{vars.LOG_PATH}}\eventMapper.log' -NewName $filenameFormat 

file created --> eventMapper-2023-23-21-10-23.log

tnavikas
  • 11
  • 2
-1

Date + Filename - NOT (Filename + Date) - otherwise it messes up file extension.

$filenameFormat = (Get-Date -Format "yyyy-MM-dd") + " " + "mybackup.zip"
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    This seems very similar to [Robert Blackwell's answer](https://stackoverflow.com/a/48231902/6045800) but will give the wrong output... Your code will create a file as `2009-12-23 mybackup.zip` while the OP asked for `mybackup 2009-12-23.zip` (which is exactly what Robert's answer outputs) – Tomerikoo Aug 16 '21 at 17:09