Delete all files and folders but exclude a subfolder

前端 未结 11 1066
忘掉有多难
忘掉有多难 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:42

    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
    
    0 讨论(0)
  • 2020-11-27 04:43

    I ran into this and found a one line command that works for me. It will delete all the folders and files on the directory in question, while retaining anything on the "excluded" list. It also is silent so it won't return an error if some files are read-only or in-use.

    @powershell Remove-item C:\Random\Directory\* -exclude "MySpecialFolder", "MySecondSpecialFolder" -force -erroraction 'silentlycontinue'
    
    0 讨论(0)
  • 2020-11-27 04:44

    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.

    0 讨论(0)
  • 2020-11-27 04:48

    I use this approach assuming you want to exclude some files or folders at root level but then you want to delete everything inside them.

    C:.
    ├───delme1
    │   │   delme.txt
    │   │
    │   └───delmetoo
    ├───delme2
    ├───folder1
    │       keepmesafe.txt
    │
    └───folder2
    

    So you want to delete everything and preserver the folder1 and folder2

    Get-ChildItem -Exclude folder1,folder2 | Remove-Item -Recurse -Force
    

    There are many other solutions but I found this easy to understand and remember.

    0 讨论(0)
  • 2020-11-27 04:49

    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.

    0 讨论(0)
提交回复
热议问题