I have a situation where a server is creating journal files (MJ00001-MJ000x) and I want to move all the files to a backup directory but need to keep the last 10 in there to get the archive. I looked at robocopy and Powershell Move-Item but the problem is the date modified is always the current day as the server looks to them if they are in the directory (hence I can't use move keeping last 10 based on date modified). I would prefer a powershell method that can look at the filename and move all except the 10 highest numbered file as I can put that into a script to stop the server service and then restart after move.
Example file structure below:
Located in C:\Folder
through to MJ00257.ext
In this example I want to move MJ0001.ext - MJ00247.ext to D:\Other_Folder\
Note that I want to keep the mainfile.ext in the directory and just the highest named MJ files.
Can anyone please help?
That's actually pretty easy using the
-SkipLast argument of
Get-ChildItem -Path "C:\Folder" -Exclude "mainfile.ext" | Sort-Object | Select-Object -SkipLast 10 |Move-Item -Destination "D:\Other_Folder\"
Get-Item "C:\temp\Source" | Get-ChildItem -Exclude "mainfile.txt" | Sort-Object | Select-Object -SkipLast 10 |Move-Item -Destination "C:\temp\Destination\"When i do a dir of c:\temp\source i have MJ000012.txt-MJ00021 (the last 10 files) but the original mainfile.txt is moved out as well. — Jun 02, 2022 at 07:37
Get-Item "C:\temp\Source" | Get-ChildItemi get all files in folder show up. then when i add -Exclude "mainfile.txt" it still shows the same output (i would expect mainfile.txt to not show in output) — Jun 02, 2022 at 07:42
External links referenced by this document: