Delete all files and folders but exclude a directo

2019-01-07 10:05发布

I have a diectory 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 dont see a way to exclude a folder.

Here is the folder structure:

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

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

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

标签: powershell
10条回答
Deceive 欺骗
2楼-- · 2019-01-07 10:27

I used this, that works perfectly for me

Get-ChildItem -Path 'C:\Temp\*' -Recurse | Where-Object {($_.FullName -notlike "*windirstat*") -and ($_.FullName -notlike "C:\Temp\GetFolderSizePortable*")} | Remove-Item -Recurse
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-07 10:27

Yes I know this is an old thread. I couldn't get any of the answers above to work in Powershell 5, so here is what I figured out:

Get-ChildItem -Path $dir -Exclude 'name_to_ignore' |
ForEach-Object {Remove-Item $_ -Recurse }

This moves the -Recurse to Remove-Item instead of where the items are found.

查看更多
不美不萌又怎样
4楼-- · 2019-01-07 10:43

In PowerShell 3.0 and below, you can try simply doing this:

Remove-Item -recurse c:\temp\* -exclude somefile.txt,foldertokeep

Unless there's some parameter I'm missing, this seems to be doing the trick...

Edit: see comments below, the behavior of Remove-Item has changed after PS3, this solution doesn't seem applicable anymore.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-07 10:43

I used the below and just removed -Recurse from the 1st line and it leaves all file and sub folders under the exclude folder list.

   Get-ChildItem -Path "PATH_GOES_HERE" -Exclude "Folder1", "Folder2", "READ ME.txt" | foreach ($_) {
       "CLEANING :" + $_.fullname
       Remove-Item $_.fullname -Force -Recurse
       "CLEANED... :" + $_.fullname
   }
查看更多
登录 后发表回答