4

I'm trying to replace line number 11 in a txt file using PowerShell.

Firstly I tried replacing a specific word, but it changed too much:

$output= (Resolve-DnsName -name name1).IPAddress 

(Get-Content "C:\test\test.txt") -replace "IPADDRESS=","IPADDRESS=$output"  | Set-Content C:\test\test.txt
3
  • What do you mean by "it change(s) to(o) much"? Commented Apr 20, 2017 at 12:45
  • It changes all lines witch word IPADDRESS= for exemple : line 5 serverIPADDRESS=0.0.0.0 line 8 computerIPADDRESS= line11 IPADDRESS= Commented Apr 20, 2017 at 12:51
  • OK. In that case, Martin Brandl's answer below is the simplest way to accomplish your aim. Commented Apr 20, 2017 at 12:52

4 Answers 4

10

If you want to replace something within a certain line, you can use the index operator on the string array that the Get-Content cmdlet returns:

$content = Get-Content "C:\test\test.txt"
$content[10] = -replace "IPADDRESS=","IPADDRESS=$output" 
$content | Set-Content C:\test\test.txt
Sign up to request clarification or add additional context in comments.

4 Comments

How can we do it as a one-liner that can be used in a Nmake file? Nmake needs simple commands, like mv a.txt b.txt.
You can just concat the lines with a semicolon ;-)
$content[10] = -replace "IPADDRESS=","IPADDRESS=$output" doesn't appear to work anymore -replace : The term '-replace' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name.
See @takeoff127 answer below if the above comment applies to you.
3

For anyone finding that the above answer doesn't work for them, this works:

$content = Get-Content "C:\test\test.txt"
$contentUpdate = $content[10] -replace "IPADDRESS=","IPADDRESS=$output" 
Set-Content C:\test\test.txt $contentUpdate

Comments

0
$content = Get-Content "$file"
$content[$line - 1] = ($content[$line - 1] -replace "IPADDRESS=","IPADDRESS=$output")
Set-Content "$file" $content

This one worked for me.

Comments

0

PowerShell 7+
$output="127.0.0.1"

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

$content[10] =$content[10] -replace "IPADDRESS=","IPADDRESS=$output"

$content| Out-File "C:\test\test.txt"

Comments

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.