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?

4

2 回答 2

3

也许这会帮助你:

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

之前:“3_File8_NOT_DONE.sql

之后:“3_File8.sql”

于 2019-05-07T13:28:52.613 回答
2

为了获得您想要的列表,它将与此解决方案一起使用

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

请注意,您过滤 Get-ChildItem 以便仅重命名以“3”开头并以“.sql”结尾的文件。@Lndngr 的解决方案将从所有文件中删除“_NOT_DONE”。

于 2019-05-07T13:42:01.570 回答