Mrchief
Mrchief

Reputation: 76218

Powershell script to delete files not specified in a list

I have a list of filenames in a text file like this:

f1.txt
f2
f3.jpg

How do I delete everything else from a folder except these files in Powershell?

Pseudo-code:

Upvotes: 16

Views: 14346

Answers (3)

x0n
x0n

Reputation: 52420

Data:

-- begin exclusions.txt --
a.txt
b.txt
c.txt
-- end --

Code:

# read all exclusions into a string array
$exclusions = Get-Content .\exclusions.txt

dir -rec *.* | Where-Object {
   $exclusions -notcontains $_.name } | `
   Remove-Item -WhatIf

Remove the -WhatIf switch if you are happy with your results. -WhatIf shows you what it would do (i.e. it will not delete)

-Oisin

Upvotes: 23

user285386
user285386

Reputation:

actually this only seems to work for the first directory rather than recursing - my altered script recurses properly.

$exclusions = Get-Content .\exclusions.txt

dir -rec | where-object {-not($exclusions -contains [io.path]::GetFileName($_))} | `  
where-object {-not($_ -is [system.IO.directoryInfo])} | remove-item -whatif

Upvotes: 1

Keith Hill
Keith Hill

Reputation: 201652

If the files exist in the current folder then you can do this:

Get-ChildItem -exclude (gc exclusions.txt) | Remove-Item -whatif

This approach assumes each file is on a separate line. If the files exist in subfolders then I would go with Oisin's approach.

Upvotes: 6

Related Questions