0

Situation:

I have multiple folders and files, which looks like this:

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:

I would like to delete all the folders and files except 'folder1' and 'file1', so that I'm left with this:

C:\Users\myname\Desktop\project1\english\folder1\file1
C:\Users\myname\Desktop\project1\chinese\folder1\file1

Question:

Can this be done with Powershell?

I asked a similar question before, and a brilliant user suggested the below solution, however it only deletes files, not folders.

$toKeep = "File1", "File3"
gci startFolder -Recurse | ? { !$_.PSIsContainer } | ? { $toKeep -notcontains $_.Name } | remove-item -WhatIf
  • What happens if you change to $toKeep = "folder1" – Dave Jan 8 '13 at 8:44
  • Tried that. It doesn't delete the other folders. – xupeikai Jan 9 '13 at 5:19
  • The ? { !$_.PSIsContainer } part filters out folders, so the rest of the code only sees files. Start by removing that. – Indrek Jan 9 '13 at 8:28
3

Powershell 3:

Get-ChildItem -Path "C:\Users\myname\Desktop\project1\english\" -File -Recurse |
Where-Object { $_.Name -ne "file1.txt" -and $_.Parent -notin ("folder1","folder2") } |
Remove-Item

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.