Home > Net >  Reorganize the files of a folder according to their extensions (jpg,mp3,mpeg) and check the duplicat
Reorganize the files of a folder according to their extensions (jpg,mp3,mpeg) and check the duplicat

Time:08-29

I'm trying to reorganize the files in a folder according to their extensions (jpg,mp3,mpeg) and check for duplicates to increment something to their name to allow manipulation. My goal is to redirect mp3 files to an audio document, mpeg to video and jpg to image.

function deplacer_dossier {

$AudioDoc = "C:\mestp\media\audio\"
$VideoDoc = "C:\mestp\media\video\"
$ImageDoc = "C:\mestp\media\image\"

    $files = Get-Item -Path C:\mestp\mesFichiers\* -Include *.jpg, *mp3, *.mpeg
        Foreach ($file in $files)  {
            if ($File -Like "*.jpg") {
                while(Test-Path -Path "$ImageDoc$files") {
                    $NewImageDoc = Join-Path $ImageDoc ($file.BaseName   "_"   $i   $file.extension)
                    $i  
                    $file | Move-Item -Destination $NewImageDoc 
                }
            }
            elseif ($File -Like "*.mp3") {
                while(Test-Path -Path "$ImageDoc$files") {
                    $NewAudioDoc = Join-Path $AudioDoc ($file.BaseName   "_"   $i   $file.extension)
                    $i  
                    $file | Move-Item -Destination $NewAudioDoc 
                }
            } 
            else {
                while(Test-Path -Path "$ImageDoc$files") {
                    $NewVideoDoc = Join-Path $VideoDoc ($file.BaseName   "_"   $i   $file.extension)
                    $i  
                    $file | Move-Item -Destination $NewVideoDoc 

            }
        }

}
}

CodePudding user response:

It's best to first group the matching files via Group-Object:

Get-Item -Path C:\mestp\mesFichiers\* -Include *.jpg, *mp3, *.mpeg | 
  Group-Object Extension |
  ForEach-Object {
    # Determine the file-type-specific destination directory.
    $destDir = @{ 
         '.jpg' =  'C:\mestp\media\image'
         '.mp3' =  'C:\mestp\media\audio'
         '.mpeg' = 'C:\mestp\media\video'
    }[$_.Name]
    # Move all files of the type at hand to the destination directory,
    # avoiding duplicates by suffixing the base file name with "_" 
    # followed by a sequence number.
    $_.Group |
      Move-Item -WhatIf -Destination { 
          $i = 0
          $suffix = ''
          while (Test-Path -LiteralPath ($destFile = Join-Path $destDir ($_.BaseName   $suffix   $_.Extension))) {
            $suffix = '_'     $i
          }
          $destFile
      }
  }

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

  • Related