LoginSignup
1
1

More than 5 years have passed since last update.

bat+PowerShellでファイル一覧を取得(ファイルサイズ、タイムスタンプ、フルパス)

Last updated at Posted at 2017-08-20

軽く探したところ、TSVかつファイルサイズを取得できるものが見つからなかったので、
作りました。

用途に応じてscriptを書き換えて利用することを想定しています。
例えば、出力カラムの並び変更や増減は、1行書き換えるだけでできます。

PowerShellコードをbat内に書いて実行していますが、深い意味はありません。

listDir.bat
@powershell -NoProfile -ExecutionPolicy Unrestricted "$s=[scriptblock]::create((gc \"%~f0\"|?{$_.readcount -gt 1})-join\"`n\");&$s" %*&goto:eof
#
# ファイル一覧取得
#
#   出力項目
#     ファイル名、ファイルサイズ、更新日付、フルパスディレクトリ名 (属性、親ディレクトリ名、拡張子、フルパス も出力可。コメントアウトしてあります)
#   参考
#     http://qiita.com/yjnk/items/a69920748e96272bfd10
#   引数
#     パターン1
#       引数指定なし ※リダイレクトするとSJISで出力できる。パターン2も同様
#     パターン2
#       <検索場所>
#     パターン3
#       <検索場所> <出力TSVファイル名> ※BOMありUTF-8で出力される
#   注意
#     引数はシングルクォート「'」で囲むのが安全です。囲まない場合、例えば 「(重要)」 というディレクトリを検索しようとしたときにエラーになります。

Param($inname, $outname)
$enc="UTF8"

if ($outname) {
    $null | Out-File $outname -Encoding $enc # 空ファイル作成
}
$List=Get-ChildItem $inname -Recurse -File | Select-Object Fullname #-File のかわりに -Directory を指定するとディレクトリのみ取得。指定しないとファイルとディレクトリを取得
foreach($Row in $List)
{
    $fullname=$Row.FullName
    #$property=Get-ItemProperty $fullname # 指定するファイル名が [.txt だとエラー、 [重要].txt だと失敗してnullが返却されてしまう
    $property=Get-ItemProperty -LiteralPath $fullname
    $name=$property.Name
    $extension=$property.Extension
    $timestamp=$property.LastWriteTime
    $length=$property.Length
    $attributes=$property.Attributes

    if ($fullname) {
        # フルパスからフルパスディレクトリ名を算出
        $dir_fullpath=$(Split-Path $fullname -Parent)
        # フルパスディレクトリ名からディレクトリ名を算出
        $dir=$(Split-Path $dir_fullpath -Leaf)
    } else {
        "ERROR : fullname null [" + $Row + "]"
        continue
    }
    # 更新日付の整形
    if ($timestamp) {
        $timestamp=$timestamp.ToString('yyyy/MM/dd HH:mm:ss')
    } else {
        "ERROR : timestamp null [" + $Row + "]"
        continue
    }

    # 1行出力
    $str="$name`t$length`t$timestamp`t$dir_fullpath"
    #$str="$name`t$length`t$timestamp`t$dir_fullpath`t$attributes`t$dir`t$extension`t$fullname`t" # 全カラムの出力テスト用 & テンプレート
    #$str="$length" # ファイルサイズ出力テスト用
    if ($outname) {
        $str | Out-File $outname -Append -Encoding $enc # ファイルへ
    } else {
        $str # 標準出力へ
    }
}

関連情報

PowerShellでディレクトリのファイル一覧とタイムスタンプを取得する

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1