How do I delete the contents of multiple folders except for specific files?
For example, I have multiple folders which contain the same files, as below:
Folder1:
- File1
- File2
- File3
Folder2
- File1
- File2
- File3
Folder3
- File1
- File2
- File3
Etc.
I want to delete all files from each folder, except for File1 and File3. Can I do this with Powershell?
EDIT 1
Thank Crom! You guys are awesome!! We've figured out how to delete the files. However, I forgot to mention that I need to delete other folders also.
For example, here is what my folder structure looks like.
C:\Users\myname\Desktop\project1\english\folder1\file1
C:\Users\myname\Desktop\project1\english\folder1\file2
C:\Users\myname\Desktop\project1\english\folder1\file3
C:\Users\myname\Desktop\project1\english\folder2\file4
C:\Users\myname\Desktop\project1\english\folder2\file5
C:\Users\myname\Desktop\project1\chinese\folder1\file1
C:\Users\myname\Desktop\project1\chinese\folder1\file2
C:\Users\myname\Desktop\project1\chinese\folder1\file2
C:\Users\myname\Desktop\project1\chinese\folder2\file4
C:\Users\myname\Desktop\project1\chinese\folder2\file5
Goal: Delete everything except the following:
C:\Users\myname\Desktop\project1\english\folder1\file1
C:\Users\myname\Desktop\project1\chinese\folder1\file1
Answer
You could do something like this in PowerShell:
$toKeep = "File1", "File3"
gci startFolder -Recurse | ? { !$_.PSIsContainer } | ? { $toKeep -notcontains $_.Name } | remove-item -WhatIf
Remove the -WhatIf
when you are satisfied it will do what you want it to do.
No comments:
Post a Comment