PowerShell:刪除清單中的檔案以外的所有文件

PowerShell:刪除清單中的檔案以外的所有文件

目的:
刪除List.txt檔案中未列出的資料夾中的音訊文件

讀取List.txt與音訊資料夾中的檔案進行比較,並刪除清單中未列出的檔案。

List.txt內容:

05 - Earth Wind and Fire - September (The Reflex Revision).mp3
Electric Light Orchestra - Last Train To London (Bootleg Extended Dance Remix).flac
120 - Kool & The Gang - Get Down On It (Soul Funk House Remix).wav
$files = "C:\Users\$env:username\Desktop\Logs_LUFS\List Audio Files for Normalization.txt"
$location = "C:\Users\$env:username\Desktop\LUFS Audios\"

Get-Content $files | % {               
    $result = Get-ChildItem -Recurse "$location*$_*" 
    If(!$result) {
       Remove-Item $location* $result.Fullname
    }
}

在「刪除」命令中,將顯示以下訊息:
Cannot bind argument to 'Path' parameter because it is null

!$Result當值為true時,從音訊資料夾中刪除檔案的命令是什麼 ?

答案1

PowerShell:刪除清單中的檔案以外的所有文件

以下是適用於您所描述的此任務的兩個 PowerShell 變體,我已根據您提供的詳細資訊在我這邊確認了盡可能多的模擬。

電源外殼1

$files = Get-Content "C:\Users\$env:username\Desktop\Logs_LUFS\List Audio Files for Normalization.txt";
$location = "C:\Users\$env:username\Desktop\LUFS Audios\";
Get-ChildItem -Recurse $location -File -Exclude $files | Remove-Item;

電源外殼2

$files = Get-Content "C:\Users\$env:username\Desktop\Logs_LUFS\List Audio Files for Normalization.txt";
$location = "C:\Users\$env:username\Desktop\LUFS Audios\";
             
Get-ChildItem -Recurse $location -File | %{
    If($_.Name -notin $files ){ Remove-Item -LiteralPath $_.FullName -Force; };
    };

支持資源

相關內容