Simple PS script to copy files from one share to another

XCopy is great but sometimes you need something a little more powerful. Powershell can give you the ability to perform more complex manipulations.

Here we’re finding the previous weekday and using it to find, copy and rename a set of files into an automated regression testing environment.

$SourceFolder = "\\ProductionServer\ShareName"
$DestinationFolder = "\\CIServer\ShareName"

#Get Previous Weekday
$d = Get-Date

$offset = ($d.DayOfWeek.value__ + 5) % 7
$d1 = [math]::Floor([int]$offset / [int]5)
$d2 = [math]::Floor([int]$offset / [int]6)

#DatePattern we're looking for
$DatePattern = $d.AddDays(-($d1 + $d2 + 1)).ToString('yyyyMMdd')

$DateTimeNow = (Get-Date).ToString('yyyyMMdd_HHmm')


$FileCount = Get-ChildItem "$SourceFolder" | 
    Where-Object {$_.name -like 'FILENAME_ROOT*' + $DatePattern + '*'}| 
        Measure-Object

-join($FileCount.Count, ' files found...') 

if( $FileCount.Count -gt 0){

#Get the files
$FileList = Get-ChildItem "$SourceFolder" |
   #Adjust the search pattern here
   Where-Object {$_.name -like 'FILENAME_ROOT*' + $DatePattern + '*'}|
      Select-Object

cd $DestinationFolder

foreach ($File in $FileList){

   echo "Checking file '$File'..."

   #Copy file if it doesn't exist
   $ResultExe = test-path -path "$DestinationFolder\*" -include ($File)
      if ($ResultExe -like "False"){
         "File does not exist. Copying..." + $File.$DateTimeNow.csv" 

         Copy-Item "$SourceFolder\$File" -Destination "$DestinationFolder\$File"
      }else{
         "File already exists. No action..."
      }
   }
} else {

   "There are no files to copy..."
}
echo "Script completed at: " + $DateTimeNow

Leave a Reply

Your email address will not be published. Required fields are marked *