Freitag, 28. Mai 2010

A Problem with Remove-Item $folder -recurse -force

I'm working with some testsenario, where I have repeatedly to remove a folder structure of about 3500 files of depth 8.

Remove-Item $folder -recurse -force

sometimes does not remove all the files. In some cases it yields the message, that a folder can't be deleted, because it is not empty, but when checking the folder is empty. In other not all files are removed.

To reach a clean state, I wrote the following script:


function Remove-ItemRecursiveBruteForce            
{            
    param(            
        [Parameter(Position = 0, Mandatory=$true, ValueFromPipeline=$false)]            
        [string]$folder,            
        [Parameter(Position = 1, Mandatory=$False, ValueFromPipeline=$false)]            
        $maxiterations = 20            
    )            
            
    $iteration = 0            
    while (  $iteration++ -lt   $maxiterations)            
    {            
        if (Test-Path $folder)            
        {            
            Remove-Item $folder -recurse -force -EA SilentlyContinue            
        }            
        else            
        {            
            "$folder deleted in $iteration iterations"            
            break            
        }            
    }            
    if (Test-Path $folder)            
    {            
        "$folder not empty after $iteration iterations"            
    }            
            
}            
            


I observe that it needs randomly between 2 and 11 iterations to remove my folder.

I'm using W7-32 bit and use PowerShell-ISE to run the script.

Is this problem just me, or is it OS specific. Any explanations?

Kommentare:

  1. Hey,

    I'm having the same problem... Also running Windows7 32bit...
    Did you find a different way to recursively delete a directory?

    Thanks,
    Tiberiu

    AntwortenLöschen
  2. Btw, here's how I'm doing it:
    cmd /c "rd /s /q $dir_name"

    After working with Bash, TCL, Ruby and Korn I'm realizing that Powershell is a piece of crap.

    AntwortenLöschen
  3. I've noticed that it won't work using the ISE but it will work if you type it in on the PS Command Line - weird!

    AntwortenLöschen