Rename multiple files in a folder, add a prefix (Windows)

前端 未结 8 1104
迷失自我
迷失自我 2021-01-29 18:28

I\'d like to batch rename files in a folder, prefixing the folder\'s name into the new names. i.e. files in C:\\house chores\\ will all be renamed house chore

8条回答
  •  耶瑟儿~
    2021-01-29 19:02

    I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:

    Get-ChildItem -Path . -OutVariable dirs
    foreach ($i in $dirs) { Rename-Item $i.name (""+$i.name) }
    

    This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.

    Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.

    (Disclaimer: I'm very much a PowerShell n00b.)

提交回复
热议问题