PowerShell complaining about path, But path is valid

CryptoJones picture CryptoJones · Jul 29, 2014 · Viewed 13.9k times · Source

In the following code, when $client = XRS1

if (Test-Path C:\dbbackups\cm_$client-*.full.bak){
Rename-Item -path C:\dbbackups\cm_$client-*.bak -newname cm_$client.bak
Write-Host "New file found, renamed to: cm_$client.bak"

The Test-Path statement can find C:\dbbackups\cm_xrs1-2013414.full.full.bak but -path in the Rename-Item can't.

The error I get is

Rename-Item : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation again.
At C:\Users\Aaron\Documents\0000 - PowerShell DB Update Utility\UpdateCMDatabases.ps1:167 char:1
+ Rename-Item -path C:\dbbackups\cm_$client-*.bak -newname cm_$client.bak
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], PSArgumentException
    + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand

Answer

7hibault picture 7hibault · May 5, 2015

For those who need only a one line command, please note that this is a powershell only error and that this command works just fine in the good old command prompt.

The full form of the powershell command is

ren -Path [something with a wildcard] -NewName [something else]

The error relates to the value of the Path parameter. It accepts wildcards in the path but it must resolve to a single file [1]. To use wildcards with powershell, you'll need to pipe them one by one to the rename item command. Here is an example to rename txt files to log [2]:

get-childItem *.txt | rename-item -newname { $_.name -replace '\.txt','.log' }