Moving files to appropriate location based on their extension

大兔子大兔子 提交于 2019-12-22 08:36:35

问题


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.



来源:https://stackoverflow.com/questions/5859583/moving-files-to-appropriate-location-based-on-their-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!