user1902849
user1902849

Reputation: 1141

Dynamcially copy files from folders and subfolders to destination

I have a folder

D:\Projects\PowerShell\Common

Inside Common folder, there got many sub folders and sub sub folders. What I want to achieve is to look for a csv files and copy to:

E:\Projects\PowerShell2\Common

**D:\Projects\PowerShell\Common and E:\Projects\PowerShell2\Common has same directory structure.

Example

D:\Projects\PowerShell\Common\Geo\ABC.csv

D:\Projects\PowerShell\Common\Geo\MEA.csv

D:\Projects\PowerShell\Common\AREA\ASA.csv

Copy to

E:\Projects\PowerShell2\Common\Geo\ABC.csv

E:\Projects\PowerShell2\Common\Geo\MEA.csv

E:\Projects\PowerShell2\Common\AREA\ASA.csv

I can achieve this if I specify the location exactly like below, but I want the script able to handle it dynamically instead of hard-code. if the same files exist, just replace them.

$Src = 'D:\Projects\PowerShell\Common\Geo'
$Dst = 'E:\Projects\PowerShell2\Common\Geo'

$Extension = '*.csv'

Get-ChildItem -Path $Src -Filter $Extension -Recurse |
Where-Object {!$_.PsIsContainer} |
    # For each file
    ForEach-Object 
    {
        some code
    }

Upvotes: 0

Views: 279

Answers (1)

Esperento57
Esperento57

Reputation: 17462

try this, copy and create dir in same time (if not exists)

$source='D:\Projects\PowerShell'
$destination='E:\Projects\PowerShell2'

gci $source -file -Filter "*.csv" -Recurse | 
%{$newfile=$_.Directory -replace [regex]::Escape($source), $destination; copy-item -Path $_.FullName -Destination (new-item -type directory -force $newfile)  -force -ea 0}

if you want log copied files

$source='D:\Projects\PowerShell'
$destination='E:\Projects\PowerShell2'
$logfile="c:\temp\mylog.log"

gci $source -file -Filter "*.csv" -Recurse | 
%{$newfile=$_.Directory -replace [regex]::Escape($source), $destination; copy-item -Path $_.FullName -Destination (new-item -type directory -force $newfile)  -force -ea 0 -PassThru | 
%{ $_.fullname | out-file $logfile -Append}}

Upvotes: 1

Related Questions