System Administration & Network Administration
powershell files name
Updated Wed, 07 Sep 2022 18:41:09 GMT

Need help in Moving files to the backup directory except the last 10 files based on file NAME not date modified



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
mainfile.ext
MJ00001.ext
MJ00002.ext
MJ00003.ext
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?




Solution

That's actually pretty easy using the -SkipLast argument of Select-Object:

Get-ChildItem -Path "C:\Folder" -Exclude "mainfile.ext" | Sort-Object |
    Select-Object -SkipLast 10 |Move-Item -Destination "D:\Other_Folder\"




Comments (5)

  • +0 – I'll give that a go now and upvote if all works. Thanks. — Jun 02, 2022 at 01:24  
  • +0 – It doesn't seem to exclude the mainfile.ext file and moves that to the destination directory as well. — Jun 02, 2022 at 07:24  
  • +0 – Then you have a typo somewhere. I tested this before posting it. — Jun 02, 2022 at 07:24  
  • +0 – Here is what i have tried 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  
  • +0 – it's like exclude is not working. when i type the command section by section and tell it to Get-Item "C:\temp\Source" | Get-ChildItem i 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