Powershell - 使用 CSV 作为替换操作的查找
Powershell - use CSV as a lookup for replace operation
我有一个现有脚本,它读取源文件并将某些字符替换为新字符。所以它几乎是硬编码的。
(Get-Content $path$xml_out) | Foreach-Object {$_ -replace '<ContactCode>PROP</ContactCode>','<ContactCode>OFFICE</ContactCode>'} | set-content $path$xml_out
我想做的是将旧值和新值存储在 CSV 文件中(只有 2 列),以便用户可以进行临时更改。所以我的 CSV 看起来像这样
ORGIGINAL_CODE,NEW_CODE
CAREHOME,OFFICE
PROP,EMERG
MAIN,OFFICE
DAY,OFFICE
TELE,TEL
BUSINESS,OFFICE
这是我正在执行替换的原始文件。
CAREHOME
PROP
MAIN
DAY
TELE
BUSINESS
我正在使用 import-csv 但试图使用其中包含 Get-Content 的 ForEach 循环。
$testcsv = import-csv $path\mapping.csv
ForEach ($row in $testcsv)
{
$field1 = $row.ORGIGINAL_CODE
$field2 = $row.NEW_CODE
Echo "$field1 maps to $field2"
echo "$xml_out"
(Get-Content $path$xml_out) | Foreach-Object {$_ -replace '$field1','$field2'} | set-content $path$xml_out
}
因此,不是将源文件中的 field1 替换为 field2,而是将我的代码放入其中
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
我希望以
结束
OFFICE
EMERG
OFFICE
OFFICE
TEL
OFFICE
我怀疑我没有正确转义它。
我可能更容易处理数组并在循环结束时输出。
$testcsv = Import-Csv $path\mapping.csv
$XmlIn = Get-Content $path\Scripts\XML.txt
foreach ($row in $testcsv)
{
$field1 = $row.ORGIGINAL_CODE
$field2 = $row.NEW_CODE
Write-Host "$field1 maps to $field2"
$XmlIn = $XmlIn.Replace($field1,$field2)
}
$XmlIn | Out-File $path\XML.txt
我有一个现有脚本,它读取源文件并将某些字符替换为新字符。所以它几乎是硬编码的。
(Get-Content $path$xml_out) | Foreach-Object {$_ -replace '<ContactCode>PROP</ContactCode>','<ContactCode>OFFICE</ContactCode>'} | set-content $path$xml_out
我想做的是将旧值和新值存储在 CSV 文件中(只有 2 列),以便用户可以进行临时更改。所以我的 CSV 看起来像这样
ORGIGINAL_CODE,NEW_CODE
CAREHOME,OFFICE
PROP,EMERG
MAIN,OFFICE
DAY,OFFICE
TELE,TEL
BUSINESS,OFFICE
这是我正在执行替换的原始文件。
CAREHOME
PROP
MAIN
DAY
TELE
BUSINESS
我正在使用 import-csv 但试图使用其中包含 Get-Content 的 ForEach 循环。
$testcsv = import-csv $path\mapping.csv
ForEach ($row in $testcsv)
{
$field1 = $row.ORGIGINAL_CODE
$field2 = $row.NEW_CODE
Echo "$field1 maps to $field2"
echo "$xml_out"
(Get-Content $path$xml_out) | Foreach-Object {$_ -replace '$field1','$field2'} | set-content $path$xml_out
}
因此,不是将源文件中的 field1 替换为 field2,而是将我的代码放入其中
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
$_ -replace $field1,$field2
我希望以
结束OFFICE
EMERG
OFFICE
OFFICE
TEL
OFFICE
我怀疑我没有正确转义它。
我可能更容易处理数组并在循环结束时输出。
$testcsv = Import-Csv $path\mapping.csv
$XmlIn = Get-Content $path\Scripts\XML.txt
foreach ($row in $testcsv)
{
$field1 = $row.ORGIGINAL_CODE
$field2 = $row.NEW_CODE
Write-Host "$field1 maps to $field2"
$XmlIn = $XmlIn.Replace($field1,$field2)
}
$XmlIn | Out-File $path\XML.txt