Skip to content

Instantly share code, notes, and snippets.

@kmpm
Last active September 28, 2020 07:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmpm/4f94e46e569ae0a4e688581231fa9e00 to your computer and use it in GitHub Desktop.
Save kmpm/4f94e46e569ae0a4e688581231fa9e00 to your computer and use it in GitHub Desktop.
if (Get-Module renamings) { return }
<#
.SYNOPSIS
Add parent folder as prefix to all files matching $pattern
.DESCRIPTION
Recursively, from current directory, searches for all files matching the provided pattern.
It then renames those files so that the filename gets a prefix that is name of the parent
folder. It skipps all files that already have the parent folder name as a prefix.
.PARAMETER pattern
The file pattern to search for. ex. *.JPG
.EXAMPLE
#Add the parent directory as a prefix to all jpg files
Add-DirectoryPrefix *.JPG
.NOTES
It does recurse !!!!
#>
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}}
}
Export-ModuleMember -Function Add-DirectoryPrefix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment