0


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?

Pezzz
  • 3
  • 3

1 Answers1

0

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\"
Gerald Schneider
  • 23,274
  • 8
  • 57
  • 89
  • I'll give that a go now and upvote if all works. Thanks. – Pezzz Jun 02 '22 at 01:24
  • It doesn't seem to exclude the mainfile.ext file and moves that to the destination directory as well. – Pezzz Jun 02 '22 at 07:24
  • Then you have a typo somewhere. I tested this before posting it. – Gerald Schneider Jun 02 '22 at 07:24
  • 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. – Pezzz Jun 02 '22 at 07:37
  • 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) – Pezzz Jun 02 '22 at 07:42
  • Funny, now I get the same result as you. I could have sworn that did not happen yesterday. However, please try my modification. This definitely works for me. – Gerald Schneider Jun 02 '22 at 07:53
  • we came to teh same conclusion at the same time .. Get-Childitem -Path fixed it for me ... `Get-ChildItem -Path C:\temp\source -Exclude "mainfile.txt" | Sort-Object | Select-Object -SkipLast 10 |Move-Item -Destination C:\temp\Destination` – Pezzz Jun 02 '22 at 07:55