Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Loop through sub-directories and move files

Tags:

powershell

I'm targeting simple task. I would like to create folder of constant name "jpg" in all subfolders of supplied root folder "D:Temp\IMG" and move all files in every subfolder with extension ".jpg" to that newly created "jpg" folder.

I thought I'll be able to solve this by myself without deep knowledge of powershell, but it seems I have to ask.

So far, I created this code

$Directory = dir D:\Temp\IMG\ | ?{$_.PSISContainer};
foreach ($d in $Directory) {
Write-Host "Working on directory $($d.FullName)..."
Get-ChildItem -Path "$($d.FullName)" -File -Recurse -Filter '*.jpg' |
  ForEach-Object {
      $Dest = "$($d.DirectoryName)\jpg"
      If (!(Test-Path -LiteralPath $Dest))
      {New-Item -Path $Dest -ItemType 'Directory' -Force}

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

What I'm getting out of this is infinite loop of folder "jpg" creation in every subfolder. Where is my code and logic failing here, please?

like image 836
MaxT Avatar asked Apr 02 '26 03:04

MaxT


1 Answers

The following script would do the job.

$RootFolder = "F:\RootFolder"

$SubFolders = Get-ChildItem -Path $RootFolder -Directory

Foreach($SubFolder in $SubFolders)
{ 
    $jpgPath = "$($SubFolder.FullName)\jpg"
    New-Item -Path $jpgPath -ItemType Directory -Force

    $jpgFiles = Get-ChildItem -Path $SubFolder.FullName -Filter "*.jpg"

    Foreach($jpgFile in $jpgFiles)
    {
        Move-Item -Path $jpgFile.FullName -Destination "$jpgPath\"
    }
}
like image 100
Akhilesh Avatar answered Apr 08 '26 05:04

Akhilesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!