我正在尝试删除所有没有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的txt文件,但是我不知道如何在powershell上执行该操作。
所以我猜如果我有1000套文件,伪代码将像这样:
for(i=0; i<1000; i++){ if(output_%i.txt exists) delete output_%i.jpg;}
谢谢。
答案 0 :(得分:0)
我认为应该这样做。请注意代码中的注释,并提出任何可能的问题!
# 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