A powershell script to copy files from one folder to another based on part of file name
A requirement came up for me to copy thousands of file to another drive with directories named depending on part of the file name. Â The file name has _ on it and every time there is an _ a subdirectory needs to be created . For example :
if the file name is :
C:\query\ RCP_DEV_orderlookup.sql  needs to be copied to D:\query\RCP\DEV\orderlookup.sql
C:\query \RCP_PROD_orderlookup.sql  needs to be copied to D:\query\RCP\PROD\orderlookup.sql
and so on
First I thought of writing a script in perl, but since it was in a windows system , I decided to write it in powershell. Â I am fascinated with the power of powershell !
Here is the script I wrote to accomplish that :
$SourceFolder = “C:\query\”
$targetFolder = “D:\query\”
$numFiles = (Get-ChildItem -Path $SourceFolder -Filter *.TXT).Count
$i=0
clear-host;
Write-Host ‘This script will copy ‘ $numFiles ‘ files from ‘ $SourceFolder ‘ to ‘ $targetFolder
Read-host -prompt ‘Press enter to start copying the files’
Get-ChildItem -Path $SourceFolder -Filter *.TXT | %{Â
   [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace(“_”,“\”))Â
  Â
  if(!(Test-Path -Path $destination.Directory )){Â
   New-item -Path $destination.Directory.FullName -ItemType DirectoryÂ
  }Â
   [int]$percent = $i / $numFiles * 100Â
  Â
   copy-item -Path $_.FullName -Destination $Destination.FullName
Write-Progress -Activity “Copying … ($percent %)” -status $_  -PercentComplete $percent -verbose
$i++
}
Write-Host ‘Total number of files read from directory ‘$SourceFolder ‘ is ‘ $numFiles
Write-Host ‘Total number of files that was copied to ‘$targetFolder ‘ is ‘ $i
Read-host -prompt “Press enter to complete…”
clear-host;Â
As always test it before you implement it on your system.