Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Read the text file line-by-line
  • Create a list of filenames
  • Recurse folder and its subfolders
  • If filename is not in list, delete it.
like image 747
Mrchief Avatar asked Jan 05 '10 23:01

Mrchief


People also ask

How do you delete a list of files in PowerShell?

Every object in PowerShell has a Delete() method and you can use it to remove that object. To delete files and folders, use the Get-ChildItem command and use the Delete() method on the output. Here, this command will delete a file called “testdata. txt”.

How do I delete a file in PowerShell script?

Delete Files in PowerShell using Remove-Item cmdlet In PowerShell, the Remove-Item cmdlet deletes one or more items from the list. It utilizes the path of a file for the deletion process. Using the “Remove-Item” command, you can delete files, folders, variables, aliases, registry keys, etc.

How do you delete a csv file in PowerShell?

Cmdlet. Remove-Item cmdlet is used to delete a file by passing the path of the file to be deleted.


1 Answers

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

like image 105
x0n Avatar answered Oct 04 '22 22:10

x0n