RhysC
RhysC

Reputation: 1644

Powershell v1 - deleteing all files & folders except in a named folder

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

Upvotes: 2

Views: 1907

Answers (2)

Shay Levy
Shay Levy

Reputation: 126732

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

Upvotes: 9

stej
stej

Reputation: 29449

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

Upvotes: 2

Related Questions