I want to delete some old files and keep the latest 3 copies with powershell command.
such as :
A.1.0.txt
A.3.0.txt
A.6.1.txt
A.9.2.txt
A.2.2.txt
B.1.txt
B.4.txt
B.7.4.txt
B.0.3.2.6.4.txt
....
Each file has the timestamp. It seems easy handle by bash shell,such as :
ls -t A.*txt| head -n -3 | xargs --no-run-if-empty rm
ls -t B.*txt| head -n -3 | xargs --no-run-if-empty rm
I am not good at powershell all command,is there any way to delete the old files? Could some one give me some advice?
Thanks.
CodePudding user response:
Assuming you want to delete all files in the directory except the 3 newest files, these would be the commands:
$Items = Get-ChildItem -Path "C:\Path\to\files\"
$Items | Sort-Object CreationTime | Select-Object -First ($Item.Count - 3) | Remove-Item
CodePudding user response:
Get-ChildItem -Path ./A.[0-9]*|Sort-Object CreationTime| Select-Object -First 3
or
Get-ChildItem -Path ./A.[0-9]* |Sort-Object LastWriteTime|Select-Object -first 3