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.
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.
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;
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)"}