title: PowerShell - Move specific files from source sub folders to destination with identical sub folder structure
body: <p>I am working on a PS script to move the 5 newest files by file type from a source directory to a destination directory while preserving the subfolder structure. For example I would like to move any file starting with AB_ from ParentFolder1\FolderA, ParentFolder1\FolderB, ParentFolder1\FolderC, etc to ParentFolder2\FolderA, ParentFolder2\FolderB, ParentFolder2\FolderC.</p>
  
  <p>ParentFolder1</p>
  
  <p>--FolderA</p>
  
  <p>----AB_1234.txt</p>
  
  <p>----AB_5678.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>--FolderB</p>
  
  <p>----AB_1234.txt</p>
  
  <p>----AB_5678.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>--FolderC</p>
  
  <p>----AB_1234.txt</p>
  
  <p>----AB_5678.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>----XY_9876.txt</p>
  
  <p>Is there a way to tie this into a for loop? Here is what I have so far:</p>
  
  <pre><code>$source = "C:\Test"
  $dest = "E:\archive"
  $AB = Get-ChildItem -Path $source -include AB_* -Recurse | Where-Object {-not $_.PsIsContainer}
  $XY = Get-ChildItem -Path $source -include XY_* -Recurse | Where-Object {-not $_.PsIsContainer}
  $keep = 5
  $logfile = "E:\_archive\temp\log_{0:MM-dd-yyyy}.log" -f (Get-Date)
  
  if ($AB.Count -gt $keep) {
      $AB | Sort -property LastWriteTime | Select-Object -First ($AB.Count - $keep) | Move-Item -destination $dest\AB -Force -Verbose
      }
  Else
      {"No AB_ files to archive." | Out-File $LogFile -Append -Force}
  
  if ($XY.Count -gt $keep) {
      $XY | Sort -property LastWriteTime | Select-Object -First ($XY.Count - $keep) | Move-Item -destination $dest\XY -Force -Verbose
      }
  Else
      {"No XY_ files to archive." | Out-File $LogFile -Append -Force}
  </code></pre>