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
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.
$files.Count
to determine the count of matching files.-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.
$files = ...
); see GitHub issue #3154 for a discussion.