views:

66

answers:

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  A: 

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 ;)

stej
Thanks Stej, yup this also works. Thanks its a nice generic function
RhysC
+2  A: 

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

Shay Levy
clean and it works. You, my friend, are a good man.
RhysC