2

I want to delete all the content and the children of a given root folder, however i want to keep some files (the logs), which all reside in a logs folder What is the elegant way of doing this in powershell. Currently i am doing it in multile steps, surely this can be done easily... i have a feeling my oo-ness/language bias is getting in the way

eg
c:\temp
c:\temp\logs
c:\temp\logs\mylog.txt
c:\temp\logs\myotherlog.log
c:\temp\filea.txt
c:\temp\fileb.txt
c:\temp\folderA...
c:\temp\folderB...

after delete should just be
c:\temp
c:\temp\logs
c:\temp\logs\mylog.txt
c:\temp\logs\myotherlog.log

this should be simple; i think 12:47am-itis is getting me...

Thanks in advance

RhysC

1
  • Is there any problem with my solution? Asking because you haven't commented on it nor accepted ;) Commented Feb 13, 2010 at 9:30

2 Answers 2

9

dir c:\temp | where {$_.name -ne 'logs'}| Remove-Item -Recurse -force

Sign up to request clarification or add additional context in comments.

Comments

2

Here is a general solution:

function CleanDir($dir, $skipDir) {
    write-host start $dir
    Get-ChildItem $dir | 
        ? { $_.PsIsContainer -and $_.FullName -ne $skipDir } | 
        % { CleanDir $_.FullName $skipDir } |
        ? { $skipDir.IndexOf($_, [System.StringComparison]::OrdinalIgnoreCase) -lt 0 } |
        % { Remove-Item -Path $_ }
    Get-ChildItem $dir |
        ? { !$_.PsIsContainer } |
        Remove-Item
    $dir
}

CleanDir -dir c:\temp\delete -skip C:\temp\delete\logs

It works recursivelly. The first parameter to CleanDir is the start directory. The second one ($skipDir) is the directory that should not be deleted (and its content shouldn't be as well).

Edited: corrected confusing example ;)

1 Comment

Thanks Stej, yup this also works. Thanks its a nice generic function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.