使用 powershell 脚本复制文件夹内容并保留文件夹结构

Copying folder contents preserving the folder structure using powershell script

我有如下所示的源文件夹结构

c:\测试结果
|-- 日志
| |-- xyz.pdf
| `-- 报告
| `--rp.pdf
|-- 关键词
| |-- key.txt
| | `--pb.ea
| `-- 报告
|-- 测试
| |-- 11.pdf
| |-- 12
| `-- 日志
| |-- h1.pdf
| `-- 报告
| `-- h2.pdf
`-- 开发
    |-- 圣
    |-- 一个
    `-- 日志
        `-- 报告
            `-- h4.pdf

我需要复制所有 "Log" 文件夹,同时保持文件夹结构。目标路径是 "c:\Work\Logs\TestResults"。生成的结构应如下所示。

c:\Work\Logs\TestResults
|-- 日志
| |-- xyz.pdf
| `-- 报告
| `--rp.pdf
|-- 测试
| `-- 日志
| |-- h1.pdf
| `-- 报告
| `-- h2.pdf
`-- 开发
    `-- 日志
        `-- 报告
            `-- h4.pdf

是否有使用 powershell 脚本实现此目的的简单方法?谢谢!

编辑: 这是我到目前为止编写的代码。它展平文件夹结构但不维护层次结构。我是 Powershell 脚本的新手。请帮忙。

$baseDir = "c:\TestResults"
$outputDir = "c:\Work\Logs"
$outputLogsDir = $outputDir + "\TestResults"
$nameToFind = "Log"

$paths = Get-ChildItem $baseDir -Recurse | Where-Object { $_.PSIsContainer -and $_.Name.EndsWith($nameToFind)}

if(!(test-path $outputLogsDir))
{
   New-Item -ItemType Directory -Force -Path $outputLogsDir
}


foreach($path in $paths)
{
   $sourcePath = $path.FullName + "\*"   
   Get-ChildItem -Path $sourcePath | Copy-Item -Destination $outputLogsDir -Recurse -Container
}                 

你要的是如下图。如果其中的任何部分包含“\log”,它将复制该项目和目录。

$gci = Get-ChildItem -Path "C:\TestResults" -Recurse

Foreach($item in $gci){
    If($item.FullName -like "*\log*"){
        Copy-Item -Path $item.FullName -Destination $($item.FullName.Replace("C:\TestResults","C:\Work\Logs\TestResults")) -Force
    }
}