Search code examples
powershellpowershell-5.0

Powershell : How to delete specific format file (.xlsx only) older than X days


I am currently new at PowerShell, I want to delete .xlsx files older than X days using Powershell. I tried below

Get-ChildItem D:\temp | ? { $_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf

But above command deleted my all data (including C drive data)

Please suggest a modification or a new command. Thanks in Advance.


Solution

  • You do not appear to be filtering for xlsx files in your code. An xlsx file is not a folder so I have removed that condition from your filter. $timelimit is not defined in the code shown but will need to be of the dateTime type to enable a comparison

    Get-ChildItem d:\temp -filter "*.xlsx"| ? { $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf