我是 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
}
最佳答案
考虑到你的情况,我可能会这样做。
$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
}
关于xml - Powershell:搜索用 CSV 替换 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12533279/