根据从文件创建的文件夹将文件复制到文件夹

时间:2018-11-27 18:07:49

标签: powershell

我有一个在目录中查找的PowerShell脚本,如果有.xlsx文件类型,它将根据每种xlsx文件类型的文件名创建一个文件夹,并将该文件复制到每个文件夹中。那部分起作用。现在,我需要做的是将\\ paculfs3 \ Deptfiles \ SharedFiles \ Compliance \ Certification Creation \ Staging中的文件复制到每个文件夹中。

这是我的代码:

$SourceFolder = "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation"
$TargetFolder = "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation"

Get-ChildItem -Path $SourceFolder -Filter *.xlsx | ForEach-Object {
    $ChildPath = Join-Path -Path $_.Name.Replace('.xlsx','') -ChildPath $_.Name

    [System.IO.FileInfo]$Destination = Join-Path -Path $TargetFolder -ChildPath $ChildPath

    if (-not (Test-Path -Path $Destination.Directory.FullName)) {
        New-Item -ItemType Directory -Path $Destination.Directory.FullName
    }

    Copy-Item -Path $_.FullName -Destination $Destination.FullName
    Copy-Item -Path "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation\Staging\Compliance Webinar Certificate Template (1).docx" -Destination $Destination -Force
    Copy-Item -Path "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation\Staging\Email Mail Merge for Certificates.docx" -Destination $Destination -Force
    Copy-Item -Path "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation\Staging\Manual Attendee Info List.xlsx" -Destination $Destination -Force
}

1 个答案:

答案 0 :(得分:0)

IMO,您正在使事情变得过于复杂,只需简单地Join-Path $TargetPath $_.BaseName

就可以在没有扩展名的情况下附加名称

要减少具有相同长路径的冗余,请使用已经定义的变量。

$SourceFolder = "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation"
$TargetFolder = "\\paculfs3\Deptfiles\SharedFiles\Compliance\Certification Creation"

Get-ChildItem -Path $SourceFolder -Filter *.xlsx | ForEach-Object {
    $Destination = Join-Path -Path $TargetFolder -ChildPath $_.BaseName
    New-Item -ItemType Directory -Path $Destination -Force | Out-Null
    $_ | Copy-Item -Destination $Destination
    Copy-Item -Path "$SourceFolder\Staging\Compliance Webinar Certificate Template (1).docx" -Destination $Destination -Force
    Copy-Item -Path "$SourceFolder\Staging\Email Mail Merge for Certificates.docx" -Destination $Destination -Force
    Copy-Item -Path "$SourceFolder\Staging\Manual Attendee Info List.xlsx" -Destination $Destination -Force
}