Delete all files and folders but exclude a subfolder

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

    This would also help someone...

    Get-ChildItem -Path PATH_GOES_HERE -Recurse -Exclude "Folder1 ", "Folder2", FileName.txt | foreach ($_) {
        "CLEANING :" + $_.fullname
        Remove-Item $_.fullname -Force -Recurse
        "CLEANED... :" + $_.fullname
    }
    
    0 讨论(0)
  • 2020-11-27 04:30

    This would also help someone...

    Adding a variable for PATH_GOES_HERE that is empty or isn't defined prior can cause a recursive deletion in the user directory (or C:\windows\system32 if the script is ran as admin). I found this out the hard way and had to re-install windows.

    Try it yourself! (below will only output the file directories into a test.txt)

    Get-ChildItem -Path $dir2 -Recurse -Exclude "Folder1 ", FileName.txt | foreach ($_) {
    $_.fullname >> C:\temp\test.txt
    }
    
    0 讨论(0)
  • 2020-11-27 04:32

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

    According to MSDN Remove-Item has a known issue with the -exclude param. Use this variant instead.

    Get-ChildItem * -exclude folderToExclude | Remove-Item
    
    0 讨论(0)
  • 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.

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

    If your paths include regex special characters then you need to use the -LiteralPath option which does not allow piping. The correct solution in that case looks like this:

        Remove-Item -force -LiteralPath(    
        Get-ChildItem -Path  'C:\temp' -Recurse -exclude somefile.txt |
        Select-Object -ExpandProperty FullName |
        Where-Object { $_ -notlike 'C:\temp\foldertokeep*' } |
        Sort-Object length -Descending 
    ) 
    
    0 讨论(0)
提交回复
热议问题