[英]Dynamcially copy files from folders and subfolders to destination
I have a folder 我有一个文件夹
D:\\Projects\\PowerShell\\Common 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:
我要实现的是寻找一个csv文件并复制到:
E:\\Projects\\PowerShell2\\Common E:\\ Projects \\ PowerShell2 \\ Common
**D:\\Projects\\PowerShell\\Common and E:\\Projects\\PowerShell2\\Common has same directory structure. ** D:\\ Projects \\ PowerShell \\ Common和E:\\ Projects \\ PowerShell2 \\ Common具有相同的目录结构。
Example 例
D:\\Projects\\PowerShell\\Common\\Geo\\ABC.csv D:\\ Projects \\ PowerShell \\ Common \\ Geo \\ ABC.csv
D:\\Projects\\PowerShell\\Common\\Geo\\MEA.csv D:\\ Projects \\ PowerShell \\ Common \\ Geo \\ MEA.csv
D:\\Projects\\PowerShell\\Common\\AREA\\ASA.csv D:\\ Projects \\ PowerShell \\ Common \\ AREA \\ ASA.csv
Copy to 复制到
E:\\Projects\\PowerShell2\\Common\\Geo\\ABC.csv E:\\ Projects \\ PowerShell2 \\ Common \\ Geo \\ ABC.csv
E:\\Projects\\PowerShell2\\Common\\Geo\\MEA.csv E:\\ Projects \\ PowerShell2 \\ Common \\ Geo \\ MEA.csv
E:\\Projects\\PowerShell2\\Common\\AREA\\ASA.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
}
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}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.