2

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
CryptoJones
  • 734
  • 3
  • 11
  • 33

2 Answers2

13

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' }
7hibault
  • 2,371
  • 3
  • 23
  • 33
1

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
  }
}
Zombo
  • 1
  • 62
  • 391
  • 407
  • 2
    won't this lose files, since you're renaming all the items that match the wildcard to the same name? – Eris Jul 29 '14 at 05:29
  • 2
    @Eris that issue appears to be in the original question as well. So Steven is preserving the bug. – BSAFH Jul 29 '14 at 05:54
  • 1
    @Eris a pipe to `select -f 1` can fix it – Zombo Jul 29 '14 at 07:12
  • Thanks for the Answer Steven, it worked perfectly! The renaming files to same name was intended. Although the intent is to get the newest one and delete the rest, so I may have to go in an explicitly code for that. – CryptoJones Jul 29 '14 at 15:20