将多个字符串替换为CSV中的数据 [英] Replace multiple Strings with Data from CSV
问题描述
我所有访问点都有一个CSV(带标题),并希望通过XML Upload将它们添加到Zabbix.
I've got a CSV (with headers) from all of our access points and want to add them to Zabbix via XML Upload.
由于我不想为每个AP手动创建XML文件,因此我将尝试在PowerShell中执行此操作.但是-怎么样?
Since I don't want to create an XML file for each AP manually, I'll try to do this in PowerShell. But - how?
我已经尝试使用(Get-Content.\ Template.xml).Replace()
和 ForEach-Object
进行一些操作,但是我没有成功
I've tried some things with (Get-Content .\Template.xml).Replace()
and ForEach-Object
, but I haven't had success yet.
文件名是:
-
AP.csv
(AP列表,标头是主机名和IP):
AP.csv
(list of APs, headers are Hostname and IP):
Hostname;IP
AP1;10.29.202.101
AP2;10.29.202.102
AP3;10.29.202.103
AP4;10.29.202.104
Ap5;10.29.202.105
Template.xml
:
<hosts>
<host>
<host>Hostname</host>
<name>Hostname</name>
[...]
<interfaces>
<interface>
[...]
<ip>PIIP</ip>
[...]
</interface>
<interface>
Template.xml
具有2个称为主机名"的字符串和2个称为"PIIP"的字符串-两个主机名字符串均应替换为 AP.csv
中的1个主机名,并且两个PIIP都应替换为相关IP.
The Template.xml
has 2 strings Called "Hostname" and 2 Called "PIIP" - Both Hostname strings should be replaced with 1 Hostname from AP.csv
, and both PIIP should be replaced with the related IP.
到目前为止,我最后一次尝试是:
My Last attempt so far was:
$a = Import-Csv .\Ap.csv
$APHost = ($a).Hostname
$APIP = ($a).IP
$xml = Get-Content .\Template.xml
foreach ($row in $a) {
$xml.Replace('Hostname',$APHost).Replace('PIIP',$APIP) |
Out-File ".\Aps\$row.xml"
}
但是,此操作以1个XML文件中的所有主机名和所有IP结尾.
But this ended in all hostnames and all IPs where in 1 XML file.
我希望每个主机的末尾都有一个XML文件,其中包含主机名和相关IP.
I would like to have 1 XML file for each host at the end with hostnames and related IP.
推荐答案
示例:
$CSVData = Import-Csv "$env:userprofile\desktop\Ap.csv" -Delimiter ";"
$template = Get-Content "$env:userprofile\desktop\template.xml" -Raw
$count = 1
foreach ($row in $CSVData) {
$template.Replace("Hostname", $row.Hostname).Replace("PIIP", $row.IP) |
Out-File "$env:userprofile\desktop\$count.xml"
$count++
}
这篇关于将多个字符串替换为CSV中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!