schnipdip
schnipdip

Reputation: 151

Deleting bulk files with the same extension while preserving files with the same extension

Get-ChildItem "I:\TEMP_Dir_SSN\" | %{
    if($_.name -ne "fullpath.txt" -or $_.name -ne "SSN_FILES.txt"){
        remove-item $_.fullname
    }
}

There are two files in the same directory that I don't want to delete. I want to delete all but two .txt files. They need to be preserved in the same directory. However, the rest is garbage and can be removed.

Upvotes: 0

Views: 72

Answers (2)

henrycarteruk
henrycarteruk

Reputation: 13227

I would use the Exclude parameter to exclude the files:

Get-ChildItem "I:\TEMP_Dir_SSN" -Exclude "fullpath.txt","SSN_FILES.txt" | Remove-Item

Upvotes: 2

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

You can utilize Where-Object in your pipeline to accomplish what you're trying to do.

Get-ChildItem "I:\TEMP_Dir_SSN\" |
  Where-Object { (($_.Name -notlike 'fullpath.txt') -and
                  ($_.Name -notlike 'SSN_FILES.txt')) } |
  Remove-Item

Just a note for more terse reading/writing, you can use the built-in alias GCI and Where

Upvotes: 4

Related Questions