从使用PowerShell多个子文件夹复制文件

问题描述 投票:0回答:2

从多个子文件夹将文件复制到另一个多个子文件夹

例如:

C:\Nani\Code\Relase4\database1\tables
C:\Nani\Code\Relase1\database1\tables
C:\Nani\Code\Relase2\database1\tables
C:\Nani\Code\Relase3\cycle1\database1\tables 
C:\Nani\Code\Relase1\database1.02.tables

我有.sql文件中所有文件夹上面,我想复制到

C\Build\database1\tables

如果数据库1 \表目录中是不存在的,我必须得创建它,

$sourceFolder  = "C:\Nani\Code"
$targetFolder  = "C\Build"
Get-Childitem $sourceFolder -recurse -filter "*.sql"  -Exclude $exclude | %{
    #If destination folder doesn't exist
    if (!(Test-Path $targetFolder -PathType Container)) {
    #Create destination folder
        New-Item -Path $targetFolder -ItemType Directory -Force
    }
    Copy-Item -Path $_.FullName -Destination $targetFolder -Recurse -force 
}

上面的代码不是在创建目的地子文件夹,

powershell powershell-v2.0 powershell-v3.0
2个回答
0
投票

我一直剧本的理解非常简单和评论的部分。请确保您添加的所有验证的路径和错误处理。否则,如果任何文件被给予任何问题的话,就不会进行,将打破循环。

脚本:

#Keeping all the sources in an array
$Sources = @("C:\Nani\Code\Relase4\database1\tables",
"C:\Nani\Code\Relase1\database1\tables",
"C:\Nani\Code\Relase2\database1\tables",
"C:\Nani\Code\Relase3\cycle1\database1\tables",
"C:\Nani\Code\Relase1\database1.02.tables")

$Destination="C\Build\database1\tables\"

#Iterating each source folder
foreach($source in $sources)
{
#Getting all the sql files under an iteration folder recursively 
$files=Get-ChildItem -Path $source -Filter "*.sql" -Recurse 

    #Iterating all the files underneath a single source folder
    foreach ($file in $files) 
    {
    #Copying the files for a single folder to the destination
    Copy-Item $file.PSPath -Destination  ("$Destination" + ($file.PSParentPath | Split-Path -Leaf) + '_' + $file)
    }
}

希望能帮助到你。


0
投票

试试这个,我首先创建的每个文件夹复制文件到它。

$sourceFolder  = "C:\Nani\Code"
$targetFolder  = "C:\Build"
$sources = Get-Childitem $sourceFolder -recurse -filter "*.sql"  -Exclude $exclude | Select FullName, DirectoryName
foreach ($source in $sources)
{
    $Releasepath = [regex]::match($source.DirectoryName,'C:\\Nani\\Code\\Release\d').Value
    $split = $Releasepath.Replace("\","\\")
    $targetfolderLeaf = $source.DirectoryName -split $split | select -Last 1
    $targetfolderpath = $targetFolder+$targetfolderLeaf
    if (!(Test-Path $targetfolderpath -PathType Container)) {
    #Create destination folder
        New-Item -Path $targetfolderpath -ItemType Directory -Force
    }
    Copy-Item -Path $source.FullName -Destination $targetfolderpath -Recurse -force 
}
© www.soinside.com 2019 - 2024. All rights reserved.