If have this piece of code
if(Test-Path -Path $OUT)
{
Remove-Item $OUT -Recurse
}
New-Item -ItemType directory -Path $OUT
Sometimes
The Remove-Item
command has a known issue.
Try this instead:
if (Test-Path $OUT)
{
# if exists: empty contents and reuse the directory itself
Get-ChildItem $OUT -Recurse | Remove-Item -Recurse
}
else
{
# else: create
New-Item -ItemType Directory -Path $OUT
}
Note:
The Get-ChildItem
command only finds non-hidden files and subdirectories, so emptying out the target directory may not be complete; to include hidden items too, add -Force
.
Similarly, add -Force
to -RemoveItem
to force removal of files that have the read-only attribute set.
-Force
, emptying may again be incomplete, but you'll get non-terminating errors in this case; if you want to treat them as terminating errors, add -ErrorAction Stop
too.