0

I'm trying to use the cmdlet Rename-Item to change the file name of multiple files in a folder. This is an example of my files (there are more files in reality):

1_File1.sql
1_File2.sql
1_File3.sql
2_File4.sql
3_File5_NOT_DONE.sql
3_File6_NOT_DONE.sql
3_File7_NOT_DONE.sql
3_File8_NOT_DONE.sql
4_File9_NOT_DONE.sql
5_File10_NOT_DONE.sql
6_File11.sql
6_File12.sql

What I wan't to do is remove the _NOT_DONE part from these files:

3_File5_NOT_DONE.sql
3_File6_NOT_DONE.sql
3_File7_NOT_DONE.sql
3_File8_NOT_DONE.sql

e.g. the files starting with 3_File

I wan't the complete list to look like this when I'm done:

1_File1.sql
1_File2.sql
1_File3.sql
2_File4.sql
3_File5.sql
3_File6.sql
3_File7.sql
3_File8.sql
4_File9_NOT_DONE.sql
5_File10_NOT_DONE.sql
6_File11.sql
6_File12.sql

I have tried using this in powershell and it gets all the files, but it forces me to set the new names to a static name (see the last part of the -Replace):

Get-ChildItem *.sql | Rename-Item -NewName {$_.name -Replace '3_File.*_NOT_DONE\.sql$', '<static filename>.sql'}

I would like to use regular expressions in the last part of -Replace as well. Or maybe there is another way to make the new names keep a part of their original name?

wenzzzel
  • 643
  • 2
  • 6
  • 17

2 Answers2

4

Maybe this would help you:

Get-ChildItem 3_*.sql | Rename-Item -NewName {$_.Name -replace "_NOT_DONE", ""}

Before: "3_File8_NOT_DONE.sql

After: "3_File8.sql"

Lndngr
  • 54
  • 5
  • This only removes the `_NOT_DONE`-part from the one file starting with `3_File8`. I need it to do exacly this but for all of the files starting with `3_File` followed anything and ending with `.sql`. So that it will hit `3_File5`, `3_File6`, `3_File7` and `3_File8`. – wenzzzel May 07 '19 at 13:34
  • 1
    Okay I think I get it: `Get-ChildItem 3_*.sql | Rename-Item -NewName {$_.Name -replace "_NOT_DONE", ""}` So every File starting with "3_" will be renamed. – Lndngr May 07 '19 at 13:41
  • That's right! Looks so obvious now when I see it. Edit that into your answer and I'll put as the accepted answer :) – wenzzzel May 07 '19 at 13:47
  • 2
    Trivial fun fact. Replacing with a null is optional. `{$_.Name -replace "_NOT_DONE"}` – js2010 May 07 '19 at 14:04
2

To get you desired list, it would work with this solution

Get-ChildItem C:\temp\test\3*.sql | Rename-Item -NewName {$_.Name -replace "_NOT_DONE", ""}

Note that you filter Get-ChildItem so that only the files are renamed when they start with a "3" and end as ".sql". The solution from @Lndngr would remove the "_NOT_DONE" from all files.

Dan Stef
  • 753
  • 1
  • 10
  • 25