Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell: Move all files from same type in subfolders, to subsubfolders

I try to move all files of extension .wav from 400 different folders inside a certain root folder, to their subfolders called ‘Stems’. Meaning that each of those 400 folders inside the root folder have a subfolder called ‘Stems’.

$Dir = 'F:\PRODUCTION\Complete Projects\*'

Get-ChildItem -Path $Dir -File -Filter '*.wav' |
  ForEach-Object {
      $Dest = "$($_.DirectoryName)\*\Stems"
      If (!(Test-Path -LiteralPath $Dest))
      {New-Item -Path $Dest -ItemType 'Directory' -Force}

      Move-Item -Path $_.FullName -Destination $Dest
  }

When I select for variable $dir a specified project folder and remove the * from the $dest$ variable, as shown below, it does move the .wav files correctly to the ‘Stems’ subfolder.

$Dir = 'F:\PRODUCTION\Complete Projects\Project 392 - Woodland\'

Get-ChildItem -Path $Dir -File -Filter '*.wav' |
  ForEach-Object {
      $Dest = "$($_.DirectoryName)\*\Stems"
      If (!(Test-Path -LiteralPath $Dest))
      {New-Item -Path $Dest -ItemType 'Directory' -Force}

      Move-Item -Path $_.FullName -Destination $Dest
  }

However, I would like to be able to do this at once for different folder names, instead of 400 times per specified folder.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions?

>Solution :

If I understood correctly, you could add a -Recurse switch to Get-ChildItem to get all .wav files and them group them by their parent’s folder path, the iterate for each group of objects and move them to their respective sub-folder:

# get all wav files recursive
Get-ChildItem -Path $Dir -File -Filter '*.wav' -Recurse |
    # group them by their parent folder absolute path
    Group-Object { $_.Directory.FullName } | ForEach-Object {
        # for each group, create a destination folder
        $dest = New-Item (Join-Path $_.Name -ChildPath 'Stems') -ItemType Directory -Force
        # and move them
        $_.Group | Move-Item -Destination $dest -WhatIf
    }

You can remove the -WhatIf switch once you consider the script is doing what you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading