반응형
XML 파일 내용을 업데이트하는 PowerShell 스크립트
XML 파일을 통과하고 내용을 업데이트할 Powershell 스크립트를 만드는 것을 도와주세요.아래 예제에서는 스크립트를 사용하여 구성에서 파일 경로를 꺼내어 변경하려고 합니다.button.명령 예제C:\Prog\Laun.jar를 C:\Prog32\folder\test.jar로 변경합니다.제발 도와주세요.감사해요.
<config>
<button>
<name>Spring</name>
<command>
C:\sy32\java.exe -jar "C:\Prog\Laun.jar" YAHOO.COM --type SPNG --port 80
</command>
<desc>studies</desc>
</button>
<button>
<name>JET</name>
<command>
C:\sy32\java.exe -jar "C:\Prog\Laun.jar" YAHOO.COM --type JET --port 80
</command>
<desc>school</desc>
</button>
</config>
오래된 게시물인 건 알지만 다른 사람들에게 도움이 될 수도 있으니까요...
찾고 있는 요소를 구체적으로 알고 있는 경우 다음과 같이 요소를 지정하면 됩니다.
# Read the existing file
[xml]$xmlDoc = Get-Content $xmlFileName
# If it was one specific element you can just do like so:
$xmlDoc.config.button.command = "C:\Prog32\folder\test.jar"
# however this wont work since there are multiple elements
# Since there are multiple elements that need to be
# changed use a foreach loop
foreach ($element in $xmlDoc.config.button)
{
$element.command = "C:\Prog32\folder\test.jar"
}
# Then you can save that back to the xml file
$xmlDoc.Save("c:\savelocation.xml")
두 가지 해결책이 있습니다.xml로 읽고 다음과 같이 텍스트를 바꿀 수 있습니다.
#using xml
#get the content of this file and cast as an XML object, so we can parse it
$xml = [xml](Get-Content .\test.xml)
#find all nodes that match
$matchingNodes = $xml.SelectNodes("//command")
foreach($node in $matchingNodes){
#if the node exists, it will have a .#text value. If it exists, then replace the first bit of text with the second
$node."#text" = $node."#text".Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar")
}
#save the changes
$xml.Save("C:\Users\graimer\Desktop\test.xml")
또는 일반 텍스트 파일처럼 간단한 문자열 대체를 사용하여 동일한 작업을 훨씬 더 간단하고 빠르게 수행할 수 있습니다.저는 이것을 추천합니다.예:
#using simple text replacement
$con = Get-Content .\test.xml
$con | % { $_.Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar") } | Set-Content .\test.xml
사용해 보십시오.
$xmlFileName = "c:\so.xml"
$match = "C:\\Prog\\Laun\.jar"
$replace = "C:\Prog32\folder\test.jar"
# Create a XML document
[xml]$xmlDoc = New-Object system.Xml.XmlDocument
# Read the existing file
[xml]$xmlDoc = Get-Content $xmlFileName
$buttons = $xmlDoc.config.button
$buttons | % {
"Processing: " + $_.name + " : " + $_.command
$_.command = $_.command -Replace $match, $replace
"Now: " + $_.command
}
"Complete, saving"
$xmlDoc.Save($xmlFileName)
언급URL : https://stackoverflow.com/questions/16428559/powershell-script-to-update-xml-file-content
반응형
'code' 카테고리의 다른 글
| 자바에서 HTML 문자 엔티티를 해제하려면 어떻게 해야 합니까? (0) | 2023.08.01 |
|---|---|
| 패키지에 나열된 모든 종속성을 제거하는 방법은 무엇입니까?json(NPM)? (0) | 2023.08.01 |
| Linux에서 조건 연산자의 이상한 사용 (0) | 2023.08.01 |
| C에서 변수 사용을 등록하는 좋은 예는 무엇입니까? (0) | 2023.08.01 |
| strln이 NULL을 확인하지 않음 (0) | 2023.08.01 |