2

我是 PowerShell 和脚本/编程的初学者,但我正在尝试编写一个 PowerShell 脚本,该脚本将在目录中的每个 XML 文档中搜索在 CSV 文件的第 1 列中找到的值,并将找到的值替换为列中的值2个相同的CSV。然后脚本将需要转到 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
}
4

1 回答 1

3

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

$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
}
于 2012-09-21T16:52:10.857 回答