刪除包含某些文件的資料夾並保留其他文件

刪除包含某些文件的資料夾並保留其他文件

我有一組想要刪除的資料夾。所有這些資料夾都包含一個名為index.html.

例如,應刪除此資料夾,因為它包含一個檔案index.htmlc:\folder2\folder3\index.html

但在同一根資料夾下,有一些資料夾包含允許的文件,例如:c:\folder2\folder1\software.rar

所以我需要一個解決方案來查找所有index.html文件並將父資料夾保留為變量,然後將其刪除。

我對此進行了測試,它生成了一個不錯的列表,但刪除不起作用:

dir /ad /b /s %1 >list.txt for /f %%g in (list.txt) do if exist %%g\index.html rd /s /q %%g

答案1

視窗 10 64 位元。電源外殼 5.1

僅刪除包含以下內容的目錄index.html 為了進行測試,請清理桌面。folder2您的桌面上不應有指定的目錄。folder2將在您的桌面上建立一個名為的目錄。

pushd $HOME\Desktop;ni -itemtype directory "folder2\folder3", "folder2\folder1">$null;ni -itemtype file "folder2\folder3\index.html", "folder2\folder1\software.rar">$null;explorer .\folder2;cls 
Read-Host "    
Test files have been created on your desktop. See explorer.
Press enter key to continue"    
Get-ChildItem .\folder2\*\index.html | ForEach-Object { 
  remove-item $_.directoryname -recurse
} 
explorer .\folder2;cls 
Read-Host "    
Directories containing index.html have been deleted. See explorer.
Press enter key to delete all test files"
ri (".\folder2") -recurse
popd 
# 

答案2

電源外殼:

詳細:

$root = 'c:\TopLevel'
Get-ChildItem -path $root -filter index.html -File -Recurse | Select -expand Directory | Remove-Item -Recurse

簡潔版本:

$root = 'c:\TopLevel'
gci $root index.html -Recurse | select -expand directory | ri -Recurse

相關內容