Search code examples
powershellwindows-10powershell-7.4

Get number of deleted files in Powershell Script


I have a Powershell script run overnight to automatically delete those files which meet certain criteria.

How can I modify it to capture the number of files selected for deletion?

The statement I'm using is nice and simple and the Where-object cmdlet would fit in nicely with what I already have, if I could get it to work.

The statement I'm trying to modify is as follows:

$path = [path to containing folder]
Get-ChildItem -Path $path -File | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-10) } | Remove-Item -Force

Solution

  • Use the common -OutVariable (-ov) parameter to capture a cmdlet's output objects in a variable, in addition to sending them to the pipeline:

    # After executing this command, $files will contain the filtered files, if any.
    Get-ChildItem -Path $path -File | 
      Where-Object LastWriteTime -lt (Get-Date).AddDays(-10) -OutVariable files | 
      Remove-Item -Force -WhatIf
    

    Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.

    Note:

    • While the filtered files are captured in variable $files, note how the -OutVariable argument is just files, i.e., without the $ sigil.

      • Use $files.Count to determine the count of matching files.
      • Using -WhatIf, as shown, allows you to examine the files to be deleted ahead of time, before actually deleting them.
    • Also, I've used simplified syntax with Where-Object above.

    • Note that the -OutVariable target variable always receives a collection (of type [System.Collections.ArrayList]), even if only one or no output object is captured.

      • Surprisingly, this behavior differs from capturing output in a variable by assignment ($files = ...); see GitHub issue #3154 for a discussion.