[英]Powershell script to modify XML from a CSV file
我正在嘗試創建一個腳本 PowerShell 來修改 CSV 文件中 XML 文件節點的“密碼”值。 每個帳戶在 CSV 中都有不同的密碼。
CSV 看起來像這樣:
Computer;AccountName;Password
SERVER-01;service.testA;mdp123
SERVER-02;service.testB;mdp456
SERVER-03;service.testC;mdp789
XML 文件如下所示:
<Configuration>
<TechnicalAccounts>
<Account Id="service.testA">
<Login>service.testA</Login>
<Description>this is a description</Description>
<Password>OldPassword</Password>
</Account>
<Account Id="service.testB">
<Login>service.testB</Login>
<Description>this is a description</Description>
<Password>OldPassword</Password>
</Account>
<Account Id="service.testC">
<Login>service.testC</Login>
<Description>this is a description</Description>
<Password>OldPassword</Password>
</Account>
</TechnicalAccounts>
</Configuration>
我試圖將 CSV 中的所有數據放入一個選項卡中,然后如果“AccountName”與 XML 中的“Login”匹配,則它會更改關聯的密碼。 但我嘗試過的一切都沒有奏效。 你有什么想法? 謝謝您的幫助。
你沒有在你的問題中展示你已經嘗試過的東西(為了將來參考,這不是在 SO 上做事情的方式)。 但鑒於您的任務並不簡單,您應該嘗試以下操作:
假設您的 csv 已加載到$data
而您的 xml 已加載到$xml
,那么:
$results = $data | ConvertFrom-Csv -Delimiter ';'
#extract the relevant elements from the csv:
$results | ForEach-Object {
$User = $_.AccountName
$Password = $_.Password
}
#then use xpath to search within the xml for the target elements:
foreach($result in $results) {
$target = $result.AccountName
$exp = '//Account[./Login/text()="'+$target+'"]/Password'
$node = $xml.SelectSingleNode($exp)
$node.innerText=$result.Password
}
您可以將輸出保存到一個新文件:
$xml.Save("mynewfile.xml")
經過研究和幫助,下面的代碼對我有用。 我把它放在這里以防它可以幫助別人。
#=======================================================================
# Variables
#=======================================================================
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path
$ScriptName = $MyInvocation.MyCommand.Name
$XMLFile = "FILE.xml"
$CSVFile = "FILE.csv"
$XMLPath = "$ScriptPath\$XMLFile"
$CSVPath = "$ScriptPath\$CSVFile"
#=======================================================================
# Import files
#=======================================================================
$InputData = Get-Content -Path $CSVPath | ConvertFrom-Csv -Delimiter ";"
$XMLDocument = New-Object -TypeName System.Xml.XmlDocument
$XMLItem = Get-Item -Path $XMLPath -ErrorAction Stop
$XMLDocument.Load($TechnicalAccountXmlItem.FullName)
#=======================================================================
# Updating XML
#=======================================================================
ForEach ($Data in $InputData)
{
$Name = $Data.AccountName
$Password = $Data.Password
$XPath = '//Account[Login="{0}"]' -f $Name
$AccountNode = $XMLDocument.SelectNodes($XPath)
$AccountNode | ?{$_} | ForEach-Object {
Write-Host ("The password of the account [{0}] has been modified from [{1}] to [{2}]." -f $_.Login,$_.Password,$Password)
$_.Password = "$Password"
}
}
$XMLDocument.Save("$ScriptPath\NewFile.xml")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.