[英]Copying folder contents preserving the folder structure using powershell script
I have the source folder structure as shown below 我有如下所示的源文件夹结构
c:\TestResults |-- Log | |-- xyz.pdf | `-- Reports | `-- rp.pdf |-- Keywords | |-- key.txt | | `-- pb.ea | `-- reports |-- Test | |-- 11.pdf | |-- 12 | `-- Log | |-- h1.pdf | `-- Reports | `-- h2.pdf `-- Dev |-- st |-- ea `-- Log `-- Reports `-- h4.pdf
I need to copy all the "Log" folders while maintaining the folder structure. 我需要在保留文件夹结构的同时复制所有“日志”文件夹。 The destination path is "c:\\Work\\Logs\\TestResults". 目标路径是“ c:\\ Work \\ Logs \\ TestResults”。 The resultant structure should be as shown below. 生成的结构应如下所示。
c:\Work\Logs\TestResults |-- Log | |-- xyz.pdf | `-- Reports | `-- rp.pdf |-- Test | `-- Log | |-- h1.pdf | `-- Reports | `-- h2.pdf `-- Dev `-- Log `-- Reports `-- h4.pdf
Is there an easy way of achieving this using a powershell script? 有使用Powershell脚本实现此目标的简单方法吗? Thanks! 谢谢!
Edit: Here's the code that I have written so far. 编辑:这是我到目前为止编写的代码。 It flattens the folder structure but doesn't maintain the hierarchy. 它使文件夹结构变平,但不维护层次结构。 I am new to powershell scripting. 我是Powershell脚本的新手。 Please help. 请帮忙。
$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
}
What you are after is as below. 您所追求的如下。 it will copy the item and dir if any part of it has "\\log" in it. 它将复制项目和目录,如果其中任何部分包含“ \\ 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.