Delete all files and folders but exclude a subfolder

前端 未结 11 1125
忘掉有多难
忘掉有多难 2020-11-27 04:16

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

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 04:36

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

    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.

提交回复
热议问题