Forum Discussion
Validating PowerShell operations - Delete file
- Jun 08, 2022
Hi, Rob.
The Try..Catch method mentioned by Harm_Veenstra is the best (though there's a good chance the "catch" won't be used since ErrorAction defaults to "Continue" instead of "Stop".)
However, since you mentioned "efficient" and "no need to check the file system", here are some minor adjustments that deliver against those requirements.
- Avoid storing results in variables unless it's unavoidable;
- Leverage the -ErrorAction:Stop parameter.
Point 1 allows scripts to scale up significantly better through not churning memory and allowing the GC (garbage collector) to release objects earlier, while point 2 allows you to avoid checking the file system after the Remove-Item.
I've spaced it out here for readability, but really, this could be a one-liner.
Get-ChildItem -Path "C:\Temp\" -Filter "*.jpg" | ForEach-Object { try { $FilePath = $_.FullName; Remove-Item -Path $FilePath -ErrorAction:Stop; "Deleted $FilePath."; } catch { "Failed to delete $FilePath."; } }Cheers,
Lain
Edited to correct a typo.
Hi, Rob.
The Try..Catch method mentioned by Harm_Veenstra is the best (though there's a good chance the "catch" won't be used since ErrorAction defaults to "Continue" instead of "Stop".)
However, since you mentioned "efficient" and "no need to check the file system", here are some minor adjustments that deliver against those requirements.
- Avoid storing results in variables unless it's unavoidable;
- Leverage the -ErrorAction:Stop parameter.
Point 1 allows scripts to scale up significantly better through not churning memory and allowing the GC (garbage collector) to release objects earlier, while point 2 allows you to avoid checking the file system after the Remove-Item.
I've spaced it out here for readability, but really, this could be a one-liner.
Get-ChildItem -Path "C:\Temp\" -Filter "*.jpg" |
ForEach-Object {
try
{
$FilePath = $_.FullName;
Remove-Item -Path $FilePath -ErrorAction:Stop;
"Deleted $FilePath.";
}
catch
{
"Failed to delete $FilePath.";
}
}
Cheers,
Lain
Edited to correct a typo.
Thank you for taking the time to respond!