Renaming Files with PowerShell

我只是一个虾纸丫 提交于 2019-12-29 09:22:19

问题


I need to rename a bunch of files at once in Windows PowerShell. I read the HTG article here and it helped a little.

My problem is that It will only rename files in the top of the directory, nothing deeper. For example: There is FOLDER A and inside FOLDERA is a document and FOLDER B. Inside FOLDER B is another document. Both folders and both documents need to be renamed. The way it is working now is that FOLDER A, the document in FOLDER A, and FOLDER B are being renamed, but not the document inside FOLDER B.

My current code is:

Dir | Rename-Item –NewName { $_.name –replace “ “,”_” }

Thanks for the help!


回答1:


You need to specify the -Recurse parameter on Dir to get it to recurse e.g.:

Dir -recurse | Rename-Item -NewName {$_.Name -replace ' ','_'}

BTW this may run into a problem because you're renaming the folder (FOLDERB) that contains the document first but the item being piped that corresponds to the file in FOLDERB still has the old name. In this case, you want to rename from the bottom up. One very crude but effective (I think) way to do this is to sort the file items on their path length descending e.g.:

Dir -recurse | Sort {$_.FullName.Length} -Desc | Rename-Item {$_.Name -replace ' ','_'}


来源:https://stackoverflow.com/questions/18094615/renaming-files-with-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!