PowerShell如何根据上级目录version.txt内容批量修改XML文件
我的文件结构如下:
当前我的PowerShell工作路径定位在Folder目录下,其下的各级SubSubFolders中存有大量xml文件。我需要实现以下需求:仅当对应xml文件所属上级目录中version.txt的内容为a,且该xml文件中不存在目标行时,才在xml的匹配行后插入指定行。
我已经可以实现修改单个指定SubSubFolder下的xml文件,但无法从Folder根目录启动操作,同时兼顾version的判断条件,现有代码如下:
#here I need to add: only if version.txt content of xml file in parent folder is "a" $files = Get-ChildItem -Filter *blah.xml -Recurse | Where{!(Select-String -SimpleMatch "AdditionalLine" -Path $_.fullname -Quiet)} | Format-Table FullName foreach($file in $files) { (Get-Content $file.FullName | Foreach-Object { $_ if ($_ -match "AdditionalLineAfterThisLine") { "AdditionalLine" } }) | Set-Content $file.FullName }
解决方案
# 从当前工作目录(Folder)递归筛选所有符合条件的xml文件 $files = Get-ChildItem -Filter *blah.xml -Recurse | Where-Object { # 过滤已存在目标行的文件 if (Select-String -SimpleMatch "AdditionalLine" -Path $_.FullName -Quiet) { return $false } # 校验同目录下version.txt内容 $versionFile = Join-Path $_.DirectoryName "version.txt" if (-not (Test-Path $versionFile -PathType Leaf)) { return $false } $version = (Get-Content $versionFile -Raw).Trim() return $version -eq 'a' } foreach ($file in $files) { (Get-Content $file.FullName | ForEach-Object { $_ if ($_ -match 'AdditionalLineAfterThisLine') { 'AdditionalLine' } }) | Set-Content $file.FullName }
调整说明
- 移除原代码中错误的
Format-Table FullName语句,该命令仅用于控制台格式化输出,会破坏原文件对象结构,导致后续无法正常读取文件路径属性 - 新增version校验逻辑:自动匹配xml文件所属目录下的version.txt,先判断文件是否存在,读取内容后自动去除首尾空白字符,避免换行、空格等格式问题干扰判断
- 原有插入行的逻辑完全保留,兼容已验证的业务规则
内容的提问来源于stack exchange,提问作者Eric Klaus
相关产品推荐
相关产品推荐

