The Get-Date cmdlet gets a DateTime object that represents the current date or a date that you specify. Get-Date can format the date and time in several . NET and UNIX formats. You can use Get-Date to generate a date or time character string, and then send the string to other cmdlets or programs.
Use the GetFileName Method to Extract the Filename From a Path in PowerShell. The GetFileName method of the . NET's Path class returns the file name and extension of the specified path.
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)"}
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;
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"))
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
Use:
$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With