Copying files with Powershell + Robocopy

Copying files using Copy-Item command can be slow. The fastest copying utility in Windows is Robocopy.

Below is the script that copy all files in "D:\temp3\test" to two destinations listed in "dst-dir.csv".

Here is the script for "copy-file-to-dir.ps1"

## sample values
#
#$src = 'D:\temp3\test'
#$dst_csv = "$PSScriptRoot\dst-dir.csv"
#

param (
    [string]$src = $(Read-Host("Source directory")),
    [string]$dst_csv = $(Read-Host("Destination CSV file name (blank for default)"))
)

if ($src.Length -eq 0) {
    Write-Host "==> the source directory has not been specified. Exit."
    return
}

if (!(Test-Path $src)) {
    Write-Host "==> the source directory does not exist. Exit."
    return
}


if ($dst_csv.Length -eq 0) {
    #set default dir
    $dst_csv = "$PSScriptRoot\dst-dir.csv"
}


if (!(Test-Path $dst_csv)) {
    $dst_csv2 = "$PSScriptRoot\$dst_csv"

    # test to see if the user pass in the file name without path.
    if (!(Test-Path $dst_csv2)) {
        Write-Host "==> the CSV file does not exist. Exit."
        return
    }
    else {
        # the user pass in the file name without path
        $dst_csv = $dst_csv2
    }
}

#====================================

$dst = Import-Csv -Path $dst_csv
$item_cnt = $dst.Length

#====================================

Write-Host "=> cloning source = $src"
Write-Host "=> destination csv file $dst_csv (found $item_cnt destinations)"
Write-Host

$ans = Read-Host("Proceed with the copy process [y/n]?")

if ($ans -eq "n") {
    Write-Host "==> the process has been cancelled"
    return
}

Write-Host

Foreach ($item in $dst) {

    #$d = $dst[$i]
    $d = $item.dst_dir
       
    Write-Host -NoNewline "==> copying to $d"
       
    $cmd = "robocopy $src $d /S /E /DCOPY:T /R:10 /W:10 /NP /TEE"
    Invoke-Expression -Command $cmd | Out-Null
   
    Write-Host "=> OK"
   
}


The contents of "dst-dir.csv" file:

dst_dir
D:\temp3\apps\app1\js
D:\temp3\apps\app2\js

Comments

Popular posts from this blog

Scheduled task in Windows Task Scheduler - part 3

Create scheduled task in Windows Task Scheduler

Get all website entries in IIS