Home > Back-end >  How do I copy a file from a directory to another directory with the same name with a modified filena
How do I copy a file from a directory to another directory with the same name with a modified filena

Time:01-11

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.

CodePudding user response:

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)
}

CodePudding user response:

I also try to achieve something like that, the only thing that i cannot get to work is to put files i copy into the same folder as the file, i guess i have to make the filename a variable and put it after the dest path

  • Related