LoginSignup
0
2

More than 3 years have passed since last update.

PowerShellでファイル名をキーにフォルダ振り分け

Posted at

ファイル転送されてくるzipファイルの解凍

まず最初に躓いたのがzipファイルの解凍の方法でした。
PowerShellのバージョンアップで標準機能として搭載されましたが、以前はunzip使ってました。
最近のバージョンだと下記のコマンドで解凍できました。

Unzip.ps1
[String]$FROM="解凍元zipファイルパス"
[String]$TO="解凍先フォルダパス"
Expand-Archive -Path $FROM -DestinationPath $TO -Force

ファイル名一覧からキー情報を抜き出す

解凍したcsvファイルの一覧からネーミングルールに沿った文字列をキーとして取得します。
取得したキーをソートすると同時にユニークなものに絞ります。

GetUniqueKey.ps1
$LIST = @(Get-ChildItem -include [0-9]*.csv -name $TO) -as [String[]]
foreach($FILE_NAME in $LIST){
    [String[]]$UNIQUE_KEY += $FILE_NAME.Substring(10,7)
}
$UNIQUE_KEY = $UNIQUE_KEY | Sort-Object | Get-Unique

キー情報を元にフォルダを作成しファイルを移動させる

上で作成したユニークなキー毎にフォルダを作成し、ファイル名にキーを含むファイルを移動させます。

MoveFile.ps1
foreach($FOLDER in $UNIQUE_KEY){
    [String]$MAKE_FOLDER=$TO + "\" + $FOLDER
    if(!(Test-Path $MAKE_FOLDER)){
        New-Item $MAKE_FOLDER -itemType Directory
    }
    [String]$CSV=$TO + "\*" + $FOLDER + "*.csv"
    Move-Item $CSV $MAKE_FOLDER -force
}
0
2
0

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
0
2