Powershell:搜索 将 XML 替换为 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
}

最新更新