递归删除与文件名匹配的文件(PowerShell 脚本)

Tup*_*Tup 7 powershell batch windows-8

我一直在将旧的批处理文件转换为 powershell 脚本并取得了不错的成功。但是......我无法弄清楚在这种情况下最好和最有效的方法是什么。

这是批处理脚本:

attrib -h -s *.* /s
del /s folder.jpg
del /s albumart*.jpg
del /s desktop.ini
@pause
Run Code Online (Sandbox Code Playgroud)

基本上它会通过我的音乐文件夹和子文件夹并删除可能存在的所有垃圾(我的音乐文件夹中有它)。

这样的东西会起作用吗(快速测试后它没有但是......)?

$currentfolder = split-path -parent $MyInvocation.MyCommand.Definition
Get-ChildItem -Path $currentfolder -Include folder.jpg, albumart*.jpg, desktop.ini -File -Recurse | foreach { $_.Delete()}
Run Code Online (Sandbox Code Playgroud)

回显已删除的文件名也很好。

编辑:我在这里添加了完整的解决方案:

$currentfolder = split-path -parent $MyInvocation.MyCommand.Definition

Get-ChildItem -Path $currentfolder -Include folder.jpg, albumart*.jpg, desktop.ini -File -Recurse | foreach { echo "Deleting: $_" ; $_.Delete()}
Run Code Online (Sandbox Code Playgroud)

Ob1*_*lan 12

即使您的第二个脚本可以工作,这个脚本也更容易理解,并且可以用“更好的 PowerShell”编写:

$currentfolder = Get-Location
Get-ChildItem -Path $currentfolder -File -Include folder.jpg,albumart*.jpg,desktop.ini -Recurse | Remove-Item -Force -Verbose
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 !

  • 你实际上可以把它做成一行。```Get-ChildItem -Path $(Get-Location) -File -Include folder.jpg,albumart*.jpg,desktop.ini -Recurse | Remove-Item -Force -Verbose``` (3认同)