Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

How to replace an object in text file with new value from variable

$
0
0

Hi folks. I'm trying to update a specific value in a text file with a new production version from a variable. It works but it repeats itself again and again. I only want to change this value in line 360. Thanks!

Original line i want to change, version # is in bold, which is what i want to change - 

<row><td>ProductVersion</td><td>1.2.4.0</td><td/></row>

 

 My code below

Write-Host = "enter new version"

$newversion = Read-Host ">>"

$content = Get-Content "C:\file.txt"

$content | 

  ForEach-Object { 

    if ($_.ReadCount -ge 360 -and $_.ReadCount -lt 361) { 

      $_ -replace '\w+',"<row><td>ProductVersion</td><td>$($newversion)</td><td/></row>" 

    } else { 

      $_ 

    } 

  } | 

  Set-Content "C:\file.txt"

 

Instead of just updating the version # one time, it does it like multiple times as below. Also present are repeating << >> signs, which should not be there. INCORRECT line below. It actually appears as one VERY long single line

<<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>><<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>><row><td>ProductVersion</td><td>1.5.0.6</td><td/></row></<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>><<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>><row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>.<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>.<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>.<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row></<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>><<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>/></<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>>

 

What i should see is just this CORRECT line below

<row><td>ProductVersion</td><td>1.5.0.6</td><td/></row>


Viewing all articles
Browse latest Browse all 6937

Trending Articles