How to recursively delete an entire directory with PowerShell 2.0?

前端 未结 18 2131
南旧
南旧 2020-12-07 07:26

What is the simplest way to forcefully delete a directory and all its subdirectories in PowerShell? I am using PowerShell V2 in Windows 7.

I have learned from severa

18条回答
  •  盖世英雄少女心
    2020-12-07 07:56

    For some reason John Rees' answer sometimes did not work in my case. But it led me in the following direction. First I try to delete the directory recursively with the buggy -recurse option. Afterwards I descend into every subdir that's left and delete all files.

    function Remove-Tree($Path)
    { 
        Remove-Item $Path -force -Recurse -ErrorAction silentlycontinue
    
        if (Test-Path "$Path\" -ErrorAction silentlycontinue)
        {
            $folders = Get-ChildItem -Path $Path –Directory -Force
            ForEach ($folder in $folders)
            {
                Remove-Tree $folder.FullName
            }
    
            $files = Get-ChildItem -Path $Path -File -Force
    
            ForEach ($file in $files)
            {
                Remove-Item $file.FullName -force
            }
    
            if (Test-Path "$Path\" -ErrorAction silentlycontinue)
            {
                Remove-Item $Path -force
            }
        }
    }
    

提交回复
热议问题