0

I need to replace the string into a file using PowerShell command.

Inside a file there are XML elements and I need to replace a particular element <version>1.0.0.0</version> with another string <version>3.0.0.0</version>.

For normal string I could write like below:

(Get-Content "D:\data.text").replace('1.0.0', '3.0.0') | Set-Content D:\data.text

How to do expression or pattern which could replace the content between <version></version> element.


EDIT:

Content of file is below:

<?xml version="1.0"?>
<package>
  <metadata>
    <id>C:\BuildAgent_SpiderWeb\work\52d106957b762949   \buildoutput\LatestPublished</id>
    <version>3.0.0</version>
    <authors>sonidha-a</authors>
  </metadata>
</package>

Need: To replace the content between ID element and Version element.

3
  • 1
    If this is XML I'd recommend using PowerShell's excellent XML editor: [xml]$data = Get-Content "D:\Data.Text"; $data.x.y.z.Version = "3.0.0.0" Commented Mar 3, 2016 at 9:10
  • If you'd rather use Replace please post a sample of your file including the version (so we can see if it's same line or if there are any surprises) Commented Mar 3, 2016 at 9:12
  • I have added details above. Please provide me getcontent command which could replace the content. Commented Mar 3, 2016 at 9:36

1 Answer 1

3

Don't do string replacements on XML data. Ever. Rainbow unicorns will die if you do.

Instead, use PowerShell's XML parser, as @Deadly-Bagel already suggested:

[xml]$xml = Get-Content 'C:\path\to\your.xml'
$xml.package.metadata.version = '3.0.0.0'
$xml.Save('C:\path\to\output.xml')
Sign up to request clarification or add additional context in comments.

4 Comments

How to execute these separate multiple lines command into powerscript ? I am new bit.
Copy/paste it into the PowerShell console or a PowerShell script.
also, I need to add <files> <file src="Published\**\**" target="content\" /> </files> content into just below the </metadata> end element. can you please tell me how to do that.
Please do not move the target. If you have a new question: post a new question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.