【问题标题】:Copying folder contents preserving the folder structure using powershell script使用powershell脚本复制文件夹内容保留文件夹结构
【发布时间】:2019-01-14 01:24:56
【问题描述】:

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

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

我需要在保持文件夹结构的同时复制所有“日志”文件夹。目标路径是“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
}                 

【问题讨论】:

标签: windows powershell powershell-3.0


【解决方案1】:

你所追求的如下。如果项目的任何部分包含“\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
    }
}

【讨论】: