0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsで名前重複しているファイルを削除するスクリプト

Posted at
# 削除対象の文字列
$deleteString = "任意の文字列"

# 任意の文字列 の後に半角スペースがある場合も考慮した正規表現
$regex = '任意の文字列\s?(\d+)'  # 「任意の文字列」の後に半角スペースが0回または1回

# ファイルをグループ化するためのハッシュテーブル
$fileGroups = @{}

# ファイル検索とグループ化(「無料高画質」を含むファイルのみ)
Get-ChildItem -Recurse | Where-Object { $_.Name -match "任意の文字列\s?\d+" -and $_.Name -like "*$deleteString*" } | ForEach-Object {
    $match = $_.Name -match $regex
    if ($match) {
        $number = $Matches[1]
        if ($fileGroups.ContainsKey($number)) {
            $fileGroups[$number] += $_.FullName
        } else {
            $fileGroups[$number] = @($_.FullName)
        }
    }
}

# 重複ファイルの削除(1つだけ残す)
$fileGroups.GetEnumerator() | Where-Object { $_.Value.Count -gt 1 } | ForEach-Object {
    $filesToDelete = $_.Value | Select-Object -Skip 1  # 1つは残す
    $filesToDelete | ForEach-Object {
        try {
            Remove-Item $_ -Force
            Write-Host ('Deleted file: {0}' -f $_)  # 文字化け防止のため英語メッセージ
        } catch {
            Write-Warning ('Failed to delete file: {0}. Error: {1}' -f $_, $_.Exception.Message)
        }
    }
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?