<<< Back to Search

File Management: Add Timestamp to File Name

Add TimeStamp to a given file name (or Path + File Name)

Add timestamp to a given File Name

# Add timestamp to a given File Name  -_-
$file = "file.txt"
$fileTimestamp = [System.IO.Path]::GetFileNameWithoutExtension($file) + "_" + `
        (get-date -format yyyyMMdd_HHmmss) + ([System.IO.Path]::GetExtension($file))

Write-Host "File: $file"
Write-Host "File with Timestamp: $fileTimestamp"


Result:

PS C:\> File: file.txt
        File with Timestamp: file_20210328_021543.txt

Add timestamp to a given Path+File Name

# Add timestamp to fileName for a given PathFile  -_- 
$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"

Result:

PS C:\> Path+File: C:\ProgramData\MyApp\file.txt
        Path+File with Timestamp: C:\ProgramData\MyApp\file_20210328_022045.txt