40

I am trying to use the Rename-Item cmdlet to do the following:

I have folder which contains "*.txt" files. Let's say 1.txt, 2.txt etc...

I want to copy files that have some prefix, rename them to *.txt and override any existing files if there are any.

example:

folder: c:\TEST

files : 1.txt, 2.txt, 3.txt, 4.txt, 5.txt, index.1.txt, index.2.txt, index.3.txt, index.4.txt, index.5.txt

I want to use rename-item to filter any index.*.txt and rename them to *.txt, and if the same file exists, replace it.

Thank you guys

WAF
  • 1,003
  • 3
  • 15
  • 31
Ilya Gurenko
  • 545
  • 1
  • 5
  • 16

2 Answers2

57

As noted by @lytledw, Move-Item -Force works great for renaming and overwriting files.

To replace the index. part of the name, you can use the -replace regex operator:

Get-ChildItem index.*.txt |ForEach-Object {
    $NewName = $_.Name -replace "^(index\.)(.*)",'$2'
    $Destination = Join-Path -Path $_.Directory.FullName -ChildPath $NewName
    Move-Item -Path $_.FullName -Destination $Destination -Force
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • With slight modifications the "Move-Item" did the trick! Cheers ! – Ilya Gurenko Aug 31 '15 at 16:18
  • I wanted to rename thousands of duplicate files that resulted from migrating my music library to a new PC from multiple backup locations, one of which automatically appended a date stamp to the filenames. I used this answer with some modifications, viz.: ` C:\Users\reyje\music\itunes\itunes media\music> Get-ChildItem "*(2017_12_14*.*" -recurse |ForEach-Object { >> $NewName = $_.Name -replace " \(2017_12_14 17_50_59 UTC\)",'' >> $Destination = Join-Path -Path $_.Directory.FullName -ChildPath $NewName >> Move-Item -Path $_.FullName -Destination $Destination -Force >> }` – PatentWookiee Dec 31 '17 at 21:23
  • The idea was to replace the literal string " (2017_12_14 17_50_59 UTC)" with nothing--the '' are two single quotation marks with nothing between them. This worked for the vast majority of the files, but for each file with square brackets in its name or path, I got errors like this: Move-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: 09 09 Old Purple Tin [9% of Pure Hea (2017_12_14 17_50_59 UTC).m4a At line:4 char:7 + Move-Item -Path $_.FullName -Destination $Destination -Force + – PatentWookiee Dec 31 '17 at 21:25
  • It seems counter-intuitive to me that characters inside a file name that is not typed would not be treated as literal string characters. – PatentWookiee Dec 31 '17 at 21:34
15

I tried the rename-item -force and it did not work. However, I was able to do move-item -force and it worked fine

lytledw
  • 161
  • 3
  • The op is asking more than one question but that is the solution for the first one. – Matt Aug 31 '15 at 13:22