เปิดและบันทึกไฟล์กำหนดค่า xml ด้วย PowerShell

ฉันกำลังพยายามสร้างสคริปต์เพื่อแก้ไขเนื้อหาของไฟล์ปรับแต่ง บันทึก และเปิดโปรแกรมที่เกี่ยวข้อง เห็นได้ชัดว่าไฟล์นี้เป็นไฟล์ xml และด้วยสคริปต์ที่ฉันสร้างขึ้น ฉันจะบันทึกมันลงในไฟล์ข้อความปกติ นั่นอาจเป็นสาเหตุที่ทำให้โปรแกรมของฉันไม่เริ่มทำงานอีกต่อไป แล้วฉันจะบันทึกเป็น xml ได้อย่างไร?

นี่คือสคริปต์:

$content = [XML](Get-Content("path\file.config"))
$content = $content.replace("IP address","Other IP address")
$content | out-file "path\file.config"

ขอบคุณล่วงหน้า

เบน


person RazZ    schedule 14.07.2017    source แหล่งที่มา
comment
ก่อนอื่น: โปรดอย่าใช้ regex บน xml ไม่มีอะไรผิดปกติกับสคริปต์ของคุณอย่างเห็นได้ชัด คุณช่วยแสดงเนื้อหาของ file.config ได้ไหม   -  person Mathias R. Jessen    schedule 14.07.2017
comment
@ MathiasR.Jessen ฉันเห็นด้วยกับความรู้สึก; โปรดจำไว้ว่า .Replace เป็นการแทนที่สตริงในขณะที่ -replace เป็นการแทนที่ regex   -  person G42    schedule 14.07.2017
comment
สวัสดีทุกคน ฉันใช้โซลูชัน @slong16 และมันใช้ได้ดี ขอบคุณ   -  person RazZ    schedule 17.07.2017


คำตอบ (1)


รหัสนี้ไม่สมเหตุสมผลเนื่องจากบางส่วนเกี่ยวข้องกับ xml และส่วนหนึ่งกับข้อความ ฉันได้พยายามอธิบายสิ่งนี้ด้วยความคิดเห็นด้านล่าง และคุณจะแก้ไขปัญหานี้ได้อย่างไร

อินพุตตัวอย่าง

<?xml version="1.0"?>
<mytag>IP address</mytag>

พังทลาย

# this line imports the file, and turns it into an XML object. so far so good.
$content = [XML](Get-Content("path\file.config"))

# this line leads to an error:
# Method invocation failed because [System.Xml.XmlDocument] does not contain a method named 'replace'
$content = $content.replace("IP address","Other IP address")

# this line will try to export the xml object (unsuccessfully)
$content | out-file "path\file.config"

วิธีที่ 1 - ถือเป็นข้อความ

$content = (Get-Content("path\file.config"))
$content = $content.replace("IP address","Other IP address")
$content | out-file "path\file.config"

วิธีที่ 2 - ถือเป็น xml

$content = [XML](Get-Content("path\file.config"))
$content = $content.mytag = "Other IP Address"
$content.OuterXml | out-file "path\file.config"
person G42    schedule 14.07.2017
comment
สวัสดี ขอบคุณสำหรับความช่วยเหลือของคุณ แต่ฉันไม่สามารถทำมันได้... ฉันเป็นมือใหม่ที่มี PS ดังนั้นอาจเป็นความผิดของฉันเอง ยังไงก็ขอบคุณนะ =) - person RazZ; 17.07.2017