powershellfile-manager

Powershell - How to copy and rename files that match regex and put them in parent folder?


I'm trying to copy, rename files, and put the copied file in the parent folder.

This line of code works inside the current folder (the file is copied, renamed with the current folder name, and placed in the parent folder):

Get-ChildItem *.jpg | Where-Object Name -match '^.*6[0-9][0-9].*$' | Copy-Item -Destination { $_.Directory.parent.FullName+"\"+$_.Directory.Name+".jpg" }

But I want to run this in the parent folder and run the code in all its subfolders.

I'm trying to make a nested loop something like this:

Get-ChildItem -Path "D:\principal\where\contains\all\folders" -Directory -PipelineVariable Directory | ForEach-Object {
    Write-Information -MessageData "Starting on folder $($Directory.Name)" -InformationAction Continue
    Get-ChildItem -Path $Directory.FullName -Recurse -Force -Filter *.jpg | Where-Object Name -match '^.*6[0-9][0-9].*$' | ForEach-Object {
        Write-Information -MessageData "Processing file $($_.Name)" -InformationAction Continue
        Copy-Item -Destination { $_.Directory.parent.FullName+"\"+$_.Directory.Name+".jpg" }
    }
    Write-Information -MessageData "Finished with folder $($Directory.Name)" -InformationAction Continue
}

But it does not work.


Solution

  • I think you're overcomplicating this task. Basically you add the parameter -Recurse to your first snippet and you're done. But since you're using the directory name to rename the files you can only rename/copy one file per folder. 🤷🏼‍♂️ ... and if you have more than one folder having the same name like a subfolder that will be another limit.

    Get-ChildItem -Filter *.jpg -File -Recurse | 
        Where-Object -Property Name -match -Value '^.*6[0-9][0-9].*$' | 
            Copy-Item -Destination { $_.Directory.parent.FullName + "\" + $_.Directory.Name + ".jpg" }
    

    You can run this code in any folder and it will process all subfolders.