Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rename-item and override if filename exists

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

like image 286
Ilya Gurenko Avatar asked Aug 31 '15 12:08

Ilya Gurenko


People also ask

How do I change a filename in PowerShell?

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression.

How do I overwrite a file in PowerShell?

PowerShell copy item exclude existing files By default when you run the PowerShell Copy-Item cmdlet, it will overwrite the file if it is already exists.

Does copy item overwrite?

The default behavior for Copy-Item is to replace existing items. The -Force switch is only to enforce replacement if for instance the destination file has the readonly attribute set. You can use -Confirm to get prompted before Copy-Item performs the operation, or you can use -WhatIf to see what the cmdlet would do.


2 Answers

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 } 
like image 150
Mathias R. Jessen Avatar answered Sep 19 '22 15:09

Mathias R. Jessen


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

like image 32
lytledw Avatar answered Sep 18 '22 15:09

lytledw