TimeStamp for file name using PowerShell

I have a path in the line,

"C: \ Temp \ mybackup.zip"

I would like to add a timestamp to the script, for example,

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

Is there an easy way to do this in PowerShell?

+62
powershell
Dec 23 '09 at 17:32
source share
4 answers

You can insert arbitrary PowerShell script code into a double-quoted string using a subexpression, such as $ ():

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

And if you get the path from another place - already as a line:

 $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 comes from Get-ChildItem output:

 Get-ChildItem *.zip | Foreach { "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"} 
+124
Dec 23 '09 at 18:03
source share
β€” -

Here is the PowerShell code that should work. You can combine most of this with fewer lines, but I wanted to keep it clear and understandable.

 [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; 
+9
Dec 23 '09 at 17:55
source share

I needed to export our security log and needed to specify the date and time in coordinated universal time. This turned out to be a problem to find 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")) 
+7
Sep 11 '13 at 19:45
source share

Using:

 $filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd") Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat 
+1
Jun 29 '16 at 13:20
source share



All Articles