Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
    
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

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
share|improve this answer
    
that gives a list of candidates .. where is the "delete"-part? – akira Jan 8 '13 at 11:53
    
good point, fixed. – Taylor Gibb Jan 8 '13 at 13:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .