Reputation: 25
I have a drive on D:\ that has folders and files laid out like this "ThisFolder\ThisFolder09.mp3" and "OtherFolder\OtherFolder13.mp3"
I need to copy them to E:\ that has folders like this (I am using the previous names here) "ThisFolder\ThisFolder.mp3" and "OtherFolder\OtherFolder.mp3"
The numbers at the end will never be more than 2 digits, they are the week number; as in there are about 52 weeks in one year, like week 2 would be the 2nd week of the year.
Using ThisFolder as an example, I need to copy "D:\ThisFolder\ThisFolder09.mp3" to "E:\ThisFolder\ThisFolder.mp3"
I thought about using Copy-Item for copying, but I couldn’t find how to remove the week number from the file name.
Upvotes: 1
Views: 59
Reputation: 440586
Santiago's helpful answer provides the crucial pointer with respect to modifying the file name as desired.
To address the aspect of wanting to keep the directory path the same as in the input file, but on a different drive, use the following - assuming the target directories on the target drive already exist:
$sourceDrive = 'D:'
$destDrive = 'E:'
Get-ChildItem -File -Recurse -LiteralPath "$sourceDrive\" -Filter *.mp3 | #" (to fix broken syntax highlighting)
Copy-Item -Destination {
$_.FullName -replace "^$sourceDrive", $destDrive -replace '\d+(?=\.mp3$)'
} -WhatIf
Note: The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
and re-execute once you're sure the operation will do what you want.
If you need to create the target directories on the target drive on demand, more work is needed:
$sourceDrive = 'D:'
$destDrive = 'E:'
Get-ChildItem -File -Recurse -LiteralPath "$sourceDrive\" -Filter *.mp3 | #" (to fix broken syntax highlighting)
Copy-Item -Destination {
$destDir = (New-Item -ErrorAction Stop -Force -Type Directory ($_.DirectoryName -replace "^$sourceDrive", $destDrive).FullName
Join-Path $destDir ($_.BaseName -replace '\d+$' + $_.Extension)
}
Upvotes: 1
Reputation: 61293
You can use -replace '\d+$'
to remove the ending digits from the files .BaseName
(the file name without its extension). For example:
$source = 'D:\ThisFolder'
$destination = 'E:\ThisFolder'
Get-ChildItem $source -File -Filter *.mp3 | Copy-Item -Destination {
Join-Path $destination (($_.BaseName -replace '\d+$') + $_.Extension)
}
Upvotes: 2