How to avoid Remove-Item PowerShell errors "process cannot access the file"?

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

You could inspect the errors given by the Remove-Item cmdlet. Use the ErrorVariable parameter on Remote-Item to store its errors in a variable, then loop through it, only displaying the errors you want.

Get-ChildItem * -Include *.csv -recurse | ForEach-Object {
    $removeErrors = @()
    $_ | Remove-Item -ErrorAction SilentlyContinue -ErrorVariable removeErrors
    $removeErrors | where-object { $_.Exception.Message -notlike '*it is being used by another process*' }
}