Question

How to rename the files matching specific keyword

I want to rename the files matching "C-00000291*.sys" via powershell.

C-00000291-00000000-00000036.sys -> C-00000291-00000000-00000036_old.sys C-00000291-00000000-00000066.sys -> C-00000291-00000000-00000066_old.sys

My files :

C-00000289-00000000-00000111.sys

C-00000291-00000000-00000036.sys

C-00000291-00000000-00000066.sys

C-00000285-00000000-00000002.sys

C-00000508-00000000-00000001.sys

and so on.

 2  315  2
1 Jan 1970

Solution

 0

As commented, when renaming files by piping from Get-ChildItem may result in unwanted re-renames, especially if the -Filter you use cannot distinguish between the original filename and the already renamed filename.

In this case, a -Filter 'C-00000291*.sys' will happily also allow a filename of C-00000291-00000000-00000036_old.sys which can make the code producing files like C-00000291-00000000-00000036_old._old._old.sys etc.

To overcome that, you either store the results from Get-ChildItem in a variable first and then loop over that array to perform the renames or (as I'm doing below) enclose the Get-ChildItem part inside brackets, so it will finish iterating the files and then do the renames:

(Get-ChildItem -Path 'D:\YourPath' -Filter 'C-00000291*.sys' -File) | 
Rename-Item -NewName {'{0}_old.sys' -f $_.BaseName}

If you'd rather use -replace to change the filename, then remember that this works with regex, so you will need to escape the dot and best also anchor it to the end of the string:

(Get-ChildItem -Path 'D:\YourPath' -Filter 'C-00000291*.sys' -File) | 
Rename-Item -NewName {$_.Name -replace '\.sys$', '_old.sys'}
2024-07-20
Theo