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 {$ -like 'FILENAME_ROOT*' + $DatePattern + '*'}| 

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

if( $FileCount.Count -gt 0){

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

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"
         "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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.