Search code examples
powershellrenamerename-item-cmdlet

Rename-item thinks variable is a path


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.


Solution

  • 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