2016年6月6日月曜日

ファイル名をもとにファイルをフォルダ分けするスクリプト

フォルダ内のファイルを一定のルールでフォルダ分けしたい場合があります。
ファイル数が多すぎるフォルダは取扱いが色々と面倒ですし。
エクスプローラの検索フィルターを併用して、手作業で何とかなる程度のファイル数ならプログラムは不要ですが、グループの数が多すぎる場合はプログラムを使った方がラクです。
dirコマンドによるファイルのリスト取得を使ってフォルダ分けするサンプルを作成しました。

こんなフォルダを今回のサンプルファイルに与えると


こんな感じで整理されます。


フォルダの中の中はこのような感じ


検索フィルターを使えば多少は整理がラクですが、今回のようなファイル数&グループ数だと手作業でやるのはしんどいです。
<job>
<script>
arg = WScript.Arguments
if(!arg.length){
WScript.Echo('引数がありません')
WScript.Quit()
}
fs = new ActiveXObject('Scripting.FileSystemObject')
shell = new ActiveXObject('WScript.Shell')
// テキストファイル入出力
Read = function(path, swCreate, swUnicode){
if(!fs.FileExists(path) && !swCreate){return ''}
var rs=fs.OpenTextFile(path,1,swCreate,swUnicode), str=rs.AtEndOfStream?'':rs.ReadAll()
rs.Close()
return str
}
Write = function(path,str,swUnicode,sw追記){
with(fs.OpenTextFile(path,sw追記?8:2,true,swUnicode)){Write(str); Close()}
}
RAS = function(path){return Read(path).split('\r\n')}
gsf2 = fs.getSpecialFolder(2)
// dirコマンドによるファイル(フォルダ)リスト取得
;(function(){
var funCore=function(path, swDir){
var pathTMP=gsf2+'/'+fs.getTempName()+'.txt'
// dirコマンドが完了するまで待機する。
shell.run('cmd /C dir /A'+(swDir?'':'-')+'D /B "'+path+'" > "'+pathTMP+'"', 0, true)
var arr=RAS(pathTMP)
// 最下行は中身無いので捨てる
arr.pop()
// 後始末
fs.deleteFile(pathTMP)
return arr
}
getFileList=function(path){ return funCore(path) }
getDirList =function(path){ return funCore(path,true) }
})();
// ファイル名ぬ含まれる複数の情報を読み取るためのパターンを作成する
regName = /([-\d]+) (\d+) ([^\.]+)\.txt$/
for(i=0,L=arg.length; i<L ;i++){
path = arg(i)
// フォルダではない引数は無視する
if(!fs.FolderExists(path)){continue}
arrFile = getFileList(path)
for(j=0,jL=arrFile.length;j<jL;j++){
// 想定外のファイル名のものは無視する
if(!arrFile[j].match(regName)){ continue }
日付 = RegExp.$1
時刻 = RegExp.$2
組み合わせ = RegExp.$3
if(!fs.FolderExists(path+'/'+組み合わせ )){ fs.CreateFolder(path+'/'+組み合わせ ) }
if(!fs.FolderExists(path+'/'+組み合わせ+'/'+日付)){ fs.CreateFolder(path+'/'+組み合わせ+'/'+日付) }
fs.MoveFile(path+'/'+arrFile[j], path+'/'+組み合わせ+'/'+日付+'/')
}
}
</script>
</job>

0 件のコメント:

コメントを投稿