148

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?

9 Answers 9

279

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)"}
Sign up to request clarification or add additional context in comments.

4 Comments

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 :-)
and if I want the time as well?
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.
29

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;

1 Comment

Thanks Tom, That was also a great help
26

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"))

2 Comments

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
@JoshBrown I changed hh to HH above. I think that's what most people will want.
9

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

Comments

3

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

Comments

0

Use:

$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat

2 Comments

perhaps $filenameFormat = "mybackup $(Get-Date -Format "yyyy-MM-dd").zip" since that matches the OP format
This will create filenameFormat = "mybackup.zip 2009-12-23". Not sure is intended or helpful...
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") }

Comments

0

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

1 Comment

This seems very similar to Robert Blackwell's answer 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)
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.