Powershell script to delete files not specified in a list Powershell script to delete files not specified in a list powershell powershell

Powershell script to delete files not specified in a list


Data:

-- begin exclusions.txt --a.txtb.txtc.txt-- end --

Code:

# read all exclusions into a string array$exclusions = Get-Content .\exclusions.txtdir -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


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.


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

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