I want to delete al开发者_Python百科l 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.logthis should be simple; i think 12:47am-itis is getting me...
Thanks in advance
RhysC
dir c:\temp | where {$_.name -ne 'logs'}| Remove-Item -Recurse -force
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 ;)
精彩评论