Moving files to appropriate location based on thei

2019-05-04 07:50发布

问题:

I have a cleanup script that moves files based on their extension to appropriate preset locations.

For example, a file with the extension .xls will be moved to ~\XLS folder, .sql to ~\SQL and so on. Here is the my script.

$dirtyfolder = "\\server\c$\Documents and Settings\user\Desktop\"
$org = "\\BACKUPS\users\"
dir $dirtyfolder -fil *.doc | mv -dest "$($org)ORG\doc"
dir $dirtyfolder -fil *.txt | mv -dest "$($org)ORG\txt"
dir $dirtyfolder -fil *.sql | mv -dest "$($org)ORG\sql"
dir $dirtyfolder -fil *.log | mv -dest "$($org)ORG\log"
dir $dirtyfolder -fil *.zip | mv -dest "$($org)ORG\zip"
dir $dirtyfolder -fil *.7z | mv -dest "$($org)ORG\zip"
dir $dirtyfolder -fil *.png | mv -dest "$($org)ORG\img"
dir $dirtyfolder -fil *.jpg | mv -dest "$($org)ORG\img"
dir $dirtyfolder -fil *.mp3 | mv -dest "$($org)ORG\mp3"

I am fully aware that this in an inelegant way to achieve my objective. So I would like to know how I can modify the script so that I can

  1. reuse repetitive code
  2. if the destination folder does not exist, it should be created.
  3. group similar extensions, like png and jpg

回答1:

Tested. A (not-recursive) solution that does not manage grouping:

ls $dirtyfolder/* | ? {!$_.PSIsContainer} | %{
  $dest = "$($org)ORG\$($_.extension)"
  if (! (Test-Path -path $dest ) ) {
    new-item $dest -type directory
  }
  mv -path $_.fullname -destination $dest 
}

Solution with grouping:

ls $dirtyfolder/* | ? {!$_.PSIsContainer} | %{
  $dest = "$($org)ORG\$(get-destbytype $_.extension)"
  if (! (Test-Path -path $dest ) ) {
    new-item $dest -type directory
  }
  mv -path $_.fullname -destination $dest 
}

where get-destbytype is the following function:

function get-destbytype($ext) {
 Switch ($ext)
 {
  {$ext -match '(jpg|png|gif)'} { "images" }
  {$ext -match '(sql|ps1)'} { "scripts" }
  default {"$ext" }
 }
}


回答2:

This is my working test

$source = "e:\source" 
$dest = "e:\dest"
$file = gci $source | ? {-not $_.psiscontainer} 
$file | group -property extension | 
        % {if(!(test-path(join-path $dest -child $_.name.replace('.','')))) { new-item -type directory $(join-path $dest -child $_.name.replace('.','')).toupper() }}
$file | % {  move-item $_.fullname -destination $(join-path $dest -child $_.extension.replace(".",""))}

The script will find all different extensions within source folder. For each extension, if the folder doesn't already exist within destination, it will be created. Last row will loop each file from source and move it to the right subfolder destination.

If you want to put images with different extensions within the same folder you need to make some further check, using an if or a switch statement.