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:
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”.
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.
Cmdlet. Remove-Item cmdlet is used to delete a file by passing the path of the file to be deleted.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With