【问题标题】:How to delete files based on condition in powershell如何根据PowerShell中的条件删除文件
【发布时间】:2019-07-11 06:59:01
【问题描述】:

我正在尝试删除所有没有具有相同文件名的 txt 文件的 jpg 文件。 例如,文件被命名为: "output_1.jpg","output_1.txt", "output_2.jpg", "output_2.txt", "output_3.jpg", "output_4.jpg","output_4.txt", ...

在这种情况下,我想删除 output_3.jpg,因为它没有带有名称的 txt 文件,但我不知道如何在 powershell 上执行此操作。

所以我猜如果我有 1000 组文件,伪代码会是这样的:

for(i=0; i<1000; i++){ if(output_%i.txt exists) delete output_%i.jpg;}

提前致谢。

【问题讨论】:

    标签: windows powershell


    【解决方案1】:

    我认为应该这样做。注意代码中的cmets,有什么问题可以问!

    # Variable to store the folder within which we are searching for them files
    [string]$folder = "C:\temp\"
    
    # Now go find all of the files in that folder with either extension
    $files = Get-ChildItem -Path $folder | Where-Object Extension -in (".txt", ".jpg")
    
    # Then group by the basename (filename without extension) and return the basenames of those where only 1 file is found
    $fileBaseNamesToDelete = ($files | Group-Object BaseName | Where-Object Count -eq 1).Name
    
    # Here's your list to delete!
    $filesToDelete = Get-ChildItem -Path $folder | Where-Object BaseName -in ($fileBaseNamesToDelete)
    
    # Go delete 'em!
    $filesToDelete | Remove-Item
    

    【讨论】:

    • 我以为我需要使用条件语句,但是哇。也非常感谢清晰的 cmets!
    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 2022-11-18
    • 2017-05-09
    • 2019-07-07
    • 2021-08-06
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多