Powershell – How to avoid Remove-Item PowerShell errors “process cannot access the file”

deploymentpowershell

We are using TfsDeployer and PowerShell script to remove the folders using Remove-Item
before deployment of a new version.
Sometimes the PS script fails with the error:

Remove-Item : Cannot remove item Services\bin: The process cannot
access the file Services\bin' because it is being used by another proc
Get-ChildItem -Path $Destination -Recurse | Remove-Item
<<<< -force -recurse + CategoryInfo :
WriteError: (C:\Program File..\Services\bin:DirectoryInfo)
[Remove-Item], IOException FullyQualifiedErrorId :
RemoveFileSystemItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand

I’ve tried to follow the answer (from: Force-remove files and directories in PowerShell fails sometimes, but not always) to pipe Get-ChildItem -Recurse into Remove-Item.

Get-ChildItem * -Include *.csv -Recurse | Remove-Item

But the error still happens periodically. We are using unlocker to manually kill the locking application, (it’s usually w3wp), but I prefer to find automated solution.

Another (not ideal) option is to-suppress-powershell-errors

 Get-ChildItem -Recurse -Force -ErrorAction SilentlyContinue

Any suggestions are welcome.

Best Answer

Late, but someone might find this useful.

In an automation script, I recurse through processes to find any that is using the path of the directory I want to delete, and kill them.

Sometimes other apps might be locking a file, so I used process explorer to find handle/dll. If is ok to kill the app, I add the kill to the script.

Then remove the dir.

        get-process | foreach{
          $pName = $_
          if ( $pName.Path -like ( $INSTALL_PATH + '*') ) {
            Stop-Process $pName.id -Force -ErrorAction SilentlyContinue
          }
        }
       Remove-Item  -Force -Recurse $INSTALL_PATH