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: