Just a quick heads up that recursive removal of files in PowerShell with Remove-Item -Recurse
is buggy and unreliable. (Even in the, as of the time of writing, latest PowerShell version v7.5.)
The underlying issue and how to reproduce it is not quite clear to me, but when running
Remove-Item -Recurse <the-directory-to-remove>
I would sometimes get errors like
Remove-Item : Cannot remove item ...
Judging from the Server Fault question linked below, this issue has been around for quite some time (the initial post is from 2010).
Moreover, the documentation actually also states that Remove-Item -Recurse
should not be used.
The buggy behavior may or may not be fixed in Windows 1909 and higher versions as the documentation suggests. I encountered it when running a Windows Server Core LTSC 2019 Docker container, however. So, it does not seem to be fixed there. I also don’t know if there is a fix for PowerShell distributions on other operating systems.
So, how do we solve this? Per the documentation, the recommended way is to find items to remove with Get-ChildItem -Recurse
and then remove them individually with Remove-Item
. For example,
Get-ChildItem * -Include *.csv -Recurse | Remove-Item
Kinda curious that a basic shell command like Remove-Item -Recurse
would be implemented defectively, but at least there is a work around.