简体   繁体   中英

How to delete files based on condition in powershell

I am trying to delete all the jpg files that do not have a txt file with the same file name. For example, files are named: "output_1.jpg","output_1.txt", "output_2.jpg", "output_2.txt", "output_3.jpg", "output_4.jpg","output_4.txt", ...

In this case, I want to delete output_3.jpg since it does not have a txt file with its name but I have no idea how to do it on powershell.

So I'm guessing the pseudocode will be like this if I have 1000 sets of files:

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

Thanks in advance.

I reckon this should do it. Pay attention to the comments in the code and ask any questions you might have!

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM