使用PowerShell提取指定环境目录下Connections子文件夹的.yaml文件
问题:提取指定子文件夹的.yaml文件并平级复制到对应目标目录
问题背景
需将QA、RESEARCH、PROD、DEV这4个环境文件夹下Connections子文件夹中的.yaml文件,复制到新目录的对应环境文件夹根目录,要求文件直接放置,不保留Connections嵌套层级。现有脚本未正确筛选目标文件,导致文件仍嵌套在子文件夹中。
当前源目录结构
- QA - Target **Connections** Folder - contains .yaml files - Several Other Folders - RESEARCH - Target **Connections** Folder - contains .yaml files - Several Other Folders - PROD - Target **Connections** Folder - Several Other Folders - DEV - Target **Connections** Folder - Several Other Folders
期望目标目录结构
- QA - .yaml files from original "qa/Connections" subfolder - RESEARCH - .yaml files from original "research/Connections" subfolder - PROD - .yaml files from original "prod/Connections" subfolder - DEV - .yaml files from original "dev/Connections" subfolder
现有问题脚本
$sourceDir = "C:\Users\hhh\appdev\powershell-scripts\TEST-REPO\hhh\data\environments" $targetDir = "C:\Users\hhh\appdev\targetfolder" Get-ChildItem $sourceDir -File -Recurse | ForEach-Object { $dest = Join-Path -Path $targetDir -ChildPath $_.DirectoryName.SubString($sourceDir.Length) if ($dest -match 'research|qa|production|global') { $null = New-Item -Path $dest -ItemType Directory -Force $_ | Copy-Item -Destination $dest -Force } }
修改后的脚本及说明
核心逻辑:精准定位每个环境下的Connections文件夹,仅提取.yaml文件,直接复制到目标目录的对应环境文件夹根目录,跳过中间层级。
$sourceDir = "C:\Users\hhh\appdev\powershell-scripts\TEST-REPO\hhh\data\environments" $targetDir = "C:\Users\hhh\appdev\targetfolder" # 遍历指定的4个环境文件夹 Get-ChildItem -Path $sourceDir -Directory -Include "QA", "RESEARCH", "PROD", "DEV" | ForEach-Object { $envFolder = $_ # 拼接当前环境下的Connections子文件夹路径 $connectionsPath = Join-Path -Path $envFolder.FullName -ChildPath "Connections" # 检查Connections文件夹是否存在 if (Test-Path -Path $connectionsPath -PathType Container) { # 获取Connections文件夹内所有.yaml文件 Get-ChildItem -Path $connectionsPath -File -Filter "*.yaml" | ForEach-Object { # 目标路径为目标目录下的对应环境文件夹 $destFolder = Join-Path -Path $targetDir -ChildPath $envFolder.Name # 确保目标文件夹存在 $null = New-Item -Path $destFolder -ItemType Directory -Force # 复制文件到目标文件夹根目录 Copy-Item -Path $_.FullName -Destination $destFolder -Force } } }
关键改进点
- 直接指定遍历的环境文件夹,避免处理无关目录
- 仅针对每个环境下的Connections子文件夹操作,精准锁定目标文件
- 只筛选
.yaml后缀文件,避免复制冗余内容 - 目标路径直接指向环境文件夹根目录,彻底消除嵌套层级
内容的提问来源于stack exchange,提问作者Ben S
相关产品推荐
相关产品推荐

