xml - Powershell:搜索用 CSV 替换 XML

标签 xml powershell csv

我是 PowerShell 和脚本/编程的初学者,但我正在尝试编写一个 PowerShell 脚本,该脚本将在目录中的每个 XML 文档中搜索 CSV 文件第 1 列中找到的值,并将找到的值替换为同一 CSV 第 2 列中的值。然后,脚本需要转到 CSV 的下一行并重复该过程,直到 CSV 第 1 列中的所有值都已被搜索并相应替换。

我已经将以下内容拼凑在一起,但我不知道如何继续。

$c = import-csv C:\somecsv.csv)
$xmls2search=get-childitem C:\somedirectory\*.xml
foreach ($xmldoc in $xmls2search)
{
  (Get-Content $xmldoc.PSPath) | 
  Foreach-Object {$_ -replace $c[i].column1name, $c[i].column2name} | 
  Set-Content $xmldoc.PSPath
}

最佳答案

考虑到你的情况,我可能会这样做。

$c = Import-Csv yourcsv.csv

Get-ChildItem *.xml | Foreach-Object {
  # Out-String in the next line lets you work with a single string rather than an
  # array of strings.
  $xmldoc = (Get-Content $_.PSPath | Out-String)

  # Loop through your CSV, updating $xmldoc with each pass
  $c | Foreach-Object {
    $xmldoc = $xmldoc -replace $_.column1name,$_.column2name
  }

  # Write the updated $xmldoc back to the original XML file's path
  $xmldoc | Set-Content $_.PSPath
}

关于xml - Powershell:搜索用 CSV 替换 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533279/

相关文章:

xml - 使用 PowerShell 将 xml 从 UTF-16 转换为 UTF-8

arrays - 为什么我不能在 Powershell 的 foreach 循环中查找数组索引?

Powershell - 如何将目录中所有文本文件的第一行提取到单个输出文件中?

java - JPA:将查询结果导出为CSV格式

python - Python 脚本可以读/写的(CSV)文件大小是否有限制?

java - 转换文件

java - 使用 XPATH 读取 XML 中的重复 block 并以特定格式进行格式化

SQL Server T-SQL 使用 FOR XML PATH 将数据导入 XML

powershell:get-winevent 没有消息数据?

excel - 保证Excel能够识别的日期格式