[英]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. 我想删除给定根文件夹的所有内容和子项,但是我想保留一些文件(日志),它们都驻留在logs文件夹中。在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
目前我正在进行多个步骤,当然这可以轻松完成...我有一种感觉我的oo-ness /语言偏见正在阻碍
eg 例如
c:\\temp C:\\ TEMP
c:\\temp\\logs C:\\ TEMP \\日志
c:\\temp\\logs\\mylog.txt C:\\ TEMP \\日志\\ mylog.txt
c:\\temp\\logs\\myotherlog.log C:\\ TEMP \\日志\\ myotherlog.log
c:\\temp\\filea.txt C:\\ TEMP \\ filea.txt
c:\\temp\\fileb.txt C:\\ TEMP \\ fileb.txt
c:\\temp\\folderA... C:\\ TEMP \\ folderA ...
c:\\temp\\folderB... C:\\ TEMP \\ FolderB中...
after delete should just be 删除后应该只是
c:\\temp C:\\ TEMP
c:\\temp\\logs C:\\ TEMP \\日志
c:\\temp\\logs\\mylog.txt C:\\ TEMP \\日志\\ mylog.txt
c:\\temp\\logs\\myotherlog.log C:\\ TEMP \\日志\\ myotherlog.log
this should be simple; 这应该很简单; i think 12:47am-itis is getting me...
我想12:47 amitis让我...
Thanks in advance 提前致谢
RhysC RhysC
dir c:\\temp | dir c:\\ temp | where {$_.name -ne 'logs'}|
其中{$ _。name -ne'logs'} | Remove-Item -Recurse -force
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. CleanDir
的第一个参数是起始目录。 The second one ( $skipDir
) is the directory that should not be deleted (and its content shouldn't be as well). 第二个(
$skipDir
)是不应删除的目录(其内容不应该也是如此)。
Edited: corrected confusing example ;) 编辑:纠正混乱的例子;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.