使用Powershell处理多个子文件夹中的文件

时间:2019-02-07 12:07:32

标签: powershell powershell-v2.0 powershell-v3.0

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

示例:

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

如果database1 \ tables目录不存在,我也必须创建它,

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

以上代码未在目标位置创建子文件夹,

2 个答案:

答案 0 :(得分: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)
    }
}

希望有帮助。

答案 1 :(得分: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 
}