Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 Rook 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
add comment

1 Answer

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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