tags:

views:

236

answers:

2

I have a path in a string

"C:\temp\mybackup.zip"

I would like instert a timestamp in that script eg

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

It there an easy way to do this in PowerShell.

+3  A: 

Here's some PS code that should work. You can combine most of this onto 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;
Tom
Thanks Tom, That was also a great help
Chris Jones
+5  A: 

You can insert arbitrary PowerShell script in a double quoted string by using a subexpression e.g. $() 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)"}
Keith Hill
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
Thanks Keith that was a great help
Chris Jones