简体   繁体   English

Powershell脚本,用于使用CSV文件作为参数来查找和替换XML文件中的值

[英]Powershell Script for finding and replacing values in an XML file using a CSV file as parameters

I've created a Powershell script which generates an XML file. 我创建了一个Powershell脚本,该脚本生成一个XML文件。 All the XML data is within the script and whatever items need to be repeated, I have them looped based on the amount of lines in the CSV (minus the header). 所有XML数据都在脚本内,无论需要重复什么项目,我都会根据CSV中的行数(减去标题)循环它们。

The next part of the script is where I'm having an issue. 脚本的下一部分是我遇到的问题。 Based on the same CSV, I'm trying now to modify the generated XML file and do a find and replace. 基于相同的CSV,我现在尝试修改生成的XML文件并进行查找和替换。 I generated which words need to be replaced from the loop such as FName1, FName2, FName3, LName1, LName2, LName3. 我生成了需要从循环中替换的单词,例如FName1,FName2,FName3,LName1,LName2,LName3。

My problem here is that whenever I try to replace these words from the CSV file, nothing gets replaced unless I hard code FName1, FName2 and so on. 我的问题是,每当我尝试从CSV文件替换这些单词时,除非我对FName1,FName2等进行硬编码,否则什么也不会被替换。

This is the code which I know is incorrect.... Basically I want it to look for any instance of FName(1,2,3 etc) and LName(1,2,3 etc) and replace it with $ _.FirstNames and $ _.LastNames. 这是我知道是不正确的代码。...基本上,我希望它查找FName(1,2,3等)和LName(1,2,3等)的任何实例,并用$ _.FirstNames and $替换它_.FirstNames and $ _.LastNames。

$c = Import-Csv test.csv

Get-ChildItem test.xml | Foreach-Object {
  $xmldoc = (Get-Content test.xml | Out-String)
  $i = 0
  $c | Foreach-Object {
    $xmldoc = $xmldoc -replace 'FName' + $i++,$_.FirstNames `
    -replace 'LName' + $i,$_.LastNames
  }

  $xmldoc | Set-Content test.xml
}

This is a portion of the test.xml file 这是test.xml文件的一部分

<ItemRef ItemID="FName1" Mandatory="No"/>
<ItemRef ItemID="FName2" Mandatory="No"/>
<ItemRef ItemID="FName3" Mandatory="No"/>
<ItemRef ItemID="LName1" Mandatory="No"/>
<ItemRef ItemID="LName2" Mandatory="No"/>
<ItemRef ItemID="LName3" Mandatory="No"/>

And this is the test.csv file: 这是test.csv文件:

FirstNames,LastNames
John,Doe
Jane,Doe
Mike,Smith
Samantha,Fox

Any help would be greatly appreciated! 任何帮助将不胜感激!

Thanks, 谢谢,

Nas 纳斯

Why are you incrementing your counter between FName and LName ? 为什么要在FNameLName之间增加计数器?
Instead of using Get-Content to read in your file, use [IO.file]::ReadAllText() . 代替使用Get-Content读取文件,请使用[IO.file]::ReadAllText() [IO.file]::ReadAllText() won't break the file into an array based on line breaks. [IO.file]::ReadAllText()不会基于换行符将文件分成数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM