noise

計算機科学や各種設定のメモ

PowerShellでファイル名でフォルダ分け

目的

"(放送時期) 番組名 第n話"の形式のファイル群をフォルダ分類します。

ソースコード

$WhatIfPreference = $False

$target_dir = ""
$season = "2014Q2"

function is_target {
  return [Regex]::IsMatch($args[0].Name,"^\($season\)")
}

function get_title {
  return [Regex]::Matches($args[0].Name,"^(\($season\)\s\S+(\s+\S+)*)\s第\d+話") | %{ $_.Groups[1].Value }
}

$arr = (gci $target_dir | ?{ $_.Attributes -eq "Archive" } | ?{ is_target $_} | %{ get_title $_ } | Sort-Object | Get-Unique)

foreach($id in $arr) {
  $dir = "$target_dir\\$id(TV)"
  if((Test-Path $dir) -eq $false) {
    New-Item $dir -ItemType Directory
  }
  if(Test-Path $dir) {
    $xs = gci $target_dir | ?{ $_.Attributes -eq "Archive" } | ?{ [Regex]::IsMatch($_.Name,"^$([Regex]::Escape($id))") }
    foreach($x in $xs) {
     Move-Item -LiteralPath $x.FullName -Destination $dir
    }
  }
}