将文件夹和子文件夹中的文件动态复制到目标

时间:2016-11-22 06:21:24

标签: powershell powershell-v4.0

我有一个文件夹

d:\项目\ PowerShell的\共同

在Common文件夹中,有许多子文件夹和子子文件夹。我想要实现的是寻找一个csv文件并复制到:

E:\项目\ PowerShell2 \共同

** D:\ Projects \ PowerShell \ Common和E:\ Projects \ PowerShell2 \ Common具有相同的目录结构。

实施例

d:\项目\ PowerShell的\共同\地理位置\ ABC.csv

d:\项目\ PowerShell的\共同\地理位置\ MEA.csv

d:\项目\ PowerShell的\共同\ AREA \ ASA.csv

复制到

E:\项目\ PowerShell2 \共同\地理位置\ ABC.csv

E:\项目\ PowerShell2 \共同\地理位置\ MEA.csv

E:\项目\ PowerShell2 \共同\ AREA \ ASA.csv

如果我指定的位置与下面完全相同,我可以实现这一点,但我希望脚本能够动态处理它而不是硬代码。如果存在相同的文件,只需替换它们。

$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
    }

1 个答案:

答案 0 :(得分:1)

试试这个,同时复制和创建目录(如果不存在)

$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}

如果您想要日志复制文件

$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}}
相关问题