【问题标题】:Powershell: Search Replace XML with CSVPowershell:搜索用 CSV 替换 XML
【发布时间】:2012-09-21 15:11:10
【问题描述】:

我是 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
}

【问题讨论】:

    标签: xml powershell csv


    【解决方案1】:

    鉴于你的情况,我可能会做这样的事情。

    $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
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 2022-11-28
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多