Skip to main content

Powershell move selected files

Powershell script below will sort files base on its last write time, it will select the files and move the selected files to another folder.

This script will remove the first 3 old files base on the lastwritetime property, quite useful to archive files or grouping large files into multiple folders.

#=====Code Snippet Start

$xfiles= Get-ChildItem d:\the_log_folder |  Sort-Object -Property @{Expression={$_.LaswriteTime}; Ascending = $true} | Select-Object -first 3 | select fullname | ft -HideTableHeaders

write $xfiles >  d:\move_files_listing.txt

ForEach ($movefiles in (Get-Content "d:\move_files_listing.txt"))

{     

  If ($movefiles[1].Length –gt 0) {

      move-item $movefiles d:\the_archive_folder

      write $movefiles

     }

}

#=====Code Snippet Ends


Code explanation:

--# Sort-Object -Property @{Expression={$_.LaswriteTime}; Ascending = $true # this will sort the files beginning from the file with the  last write time or basically the old files base on its write time.

--#  Select-Object -first 3 #self-explanatory select the first 3 files from the list adjust the number as desired

--# select fullname #get the fullpath plus the filename which is needed in move-item command

--# ft –HideTableHeaders #format table options to hide the headers which is not needed

--# write $xfiles >  d:\move_files_listing.txt #This will contains the files that will be moved or has been moved

--# If ($movefiles[1].Length –gt 0) #This line will just escape empty lines

If empty lines are not escape the move-item command will result to an error and the output will be in red color but the files have already been move.


Cheers..till next time..happy scripting.




Comments