Rename-item thinks variable is a path

user3564542 picture user3564542 · May 20, 2014 · Viewed 12k times · Source

I'm trying to rename a file but powershell thinks my variable is a string and fails.

Here is the script:

$date=(get-date -Format d)
$time=(get-date -Format t)
$source = "D:\_qapi.log"
$newfilename = "$date"+"_"+"$time"+"_qapi[SERVERNAME].log"

Rename-Item $source -NewName $newfilename

And here is the error:

Rename-Item : Cannot rename because the target specified represents a path or device name.

Anyone know I can fix this? For some reason powershell sees the $date variable in $newfilename as a path.

Answer

James Woolfenden picture James Woolfenden · May 20, 2014

Its illegal characters in the date time strings.

this works:

$date=(get-date -Format d) -replace("/")
$time=(get-date -Format t) -replace(":")
$source = "D:\_qapi.log"
$newfilename = "$date"+"_"+"$time"+"_qapi[$env:Computername].log"

Rename-Item $source -NewName $newfilename