Forum Discussion

robmo's avatar
robmo
Brass Contributor
Jun 07, 2022

Validating PowerShell operations - Delete file

Hi, What is the most accurate and efficient way to be certain PowerShell has executed a task with no discrepancies? In this case, I need to delete files with a certain extension (*.jpg). I have been...
  • LainRobertson's avatar
    Jun 08, 2022

    robmo 

     

    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.

     

    1. Avoid storing results in variables unless it's unavoidable;
    2. 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.

Resources