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

前端 未结 8 1167
迷失自我
迷失自我 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:23

    I know it's an old question but I learned alot from the various answers but came up with my own solution as a function. This should dynamically add the parent folder as a prefix to all files that matches a certain pattern but only if it does not have that prefix already.

    function Add-DirectoryPrefix($pattern) {
        # To debug, replace the Rename-Item with Select-Object
        Get-ChildItem -Path .\* -Filter $pattern -Recurse | 
            Where-Object {$_.Name -notlike ($_.Directory.Name + '*')} | 
            Rename-Item -NewName {$_.Directory.Name + '-' + $_.Name}
            # Select-Object -Property Directory,Name,@{Name = 'NewName'; Expression= {$_.Directory.Name + '-' + $_.Name}}
    }
    

    https://gist.github.com/kmpm/4f94e46e569ae0a4e688581231fa9e00

提交回复
热议问题