Jack Pettersson
Jack Pettersson

Reputation: 1666

Copying a file and adding the date to its name in PowerShell

Why doesn't this work?:

Copy-Item "C:\Logs\VPNLog.txt" "C:\Backup\VPNLog$(Get-Date -UFormat %d-%m-%Y-%R).txt"

Error message: Copy-Item : The given path's format is not supported.

For the record, this works:

Copy-Item "C:\Logs\VPNLog.txt" "C:\Backup\VPNLog.txt"

Upvotes: 3

Views: 15232

Answers (3)

Tony Hinkle
Tony Hinkle

Reputation: 4742

The %R is outputting the time formatted with colons, and filenames cannot have colons in them. To see this, simply run get-date -uformat %d-%m-%Y-%R

To get the hours, minutes, and seconds there without colons, you'll need to use a get-date command similar to the following:

get-date -uformat %d-%m-%Y-%H.%M.%S

Upvotes: 7

gravity
gravity

Reputation: 2066

You are using %R, which per the notes, provides a : character in the filename, which is not supported. Take out the %R or separate out the formatting of the date string first before appending the filename with that additional timestamp data.

Source: TechNet for Get-Date

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 59031

Its because your format contains a colon (:) which is not allowed for file names.

You can get a list of all invalid file characters using: [System.IO.Path]::GetInvalidFileNameChars()

Upvotes: 0

Related Questions