删除所有文件和文件夹但排除一个子文件夹 [英] Delete all files and folders but exclude a subfolder

查看:72
本文介绍了删除所有文件和文件夹但排除一个子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,需要删除除一小部分文件和文件夹之外的所有文件和文件夹.

I have a folder where I need to delete all files and folders except a small list of files and folders.

我已经可以排除文件列表,但看不到排除文件夹及其内容的方法.

I can already exclude a list of files, but don't see a way to exclude a folder and its contents.

这是文件夹结构:

|-C:\temp
 \-C:\temp\somefile.txt
 \-C:\temp\someotherfile.txt
| |-C:\temp\foldertodelete
   \-C:\temp\foldertodelete\file1.txt
| |-C:\temp\foldertokeep
|  \-C:\temp\foldertokeep\file2.txt

我想保留 somefile.txt 和文件夹 foldertokeep 及其内容.

I want to keep somefile.txt and the folder foldertokeep and its content.

这就是我现在所拥有的:

This is what I have right now:

Get-ChildItem -Path  'C:\temp' -Recurse -exclude somefile.txt | Remove-Item -force -recurse

这确实不会删除 somefile.txt.有没有办法从删除列表中排除文件夹 foldertokeep 及其内容?

This really does not delete somefile.txt. Is there a way to exclude folder foldertokeep and its content from the delete list?

推荐答案

Get-ChildItem -Path  'C:\temp' -Recurse -exclude somefile.txt |
Select -ExpandProperty FullName |
Where {$_ -notlike 'C:\temp\foldertokeep*'} |
sort length -Descending |
Remove-Item -force 

-recurse 开关在 Remove-Item 上不能正常工作(它会在文件夹中的所有子项目都被删除之前尝试删除文件夹).按长度降序对全名进行排序可确保在删除文件夹中的所有子项之前不会删除任何文件夹.

The -recurse switch does not work properly on Remove-Item (it will try to delete folders before all the child items in the folder have been deleted). Sorting the fullnames in descending order by length insures than no folder is deleted before all the child items in the folder have been deleted.

这篇关于删除所有文件和文件夹但排除一个子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆