Search code examples
powershellrename-item-cmdlet

PowerShell complaining about path, But path is valid


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

Solution

  • If Rename-Item does not like a wildcard, then do not give it one

    Convert-Path C:\dbbackups\cm_$client-*.full.bak | % {
      if (Test-Path $_) {
        Rename-Item $_ cm_$client.bak
      }
    }