10

I have a text file that contains a like that is similar to

Settings amount ="01:00:00"

I know how to replace the line but my issue is at the moment I am only able to replace the entire line if I know the exact contents of the line- using -match and -replace. However, is there a way that I can search for just Settings amount = and then just replace that entire line with my new setting? That way no matter what the current value is I have the power to scan and give it a different value.

This is what I have currently.

$DesiredTime = 'Settings amount="06:00:00" />'

$path = "C:\Windows\File.txt" 
 (Get-Content $path) -replace 'Settings amount="01:00:00" />', $DesiredTime | out-file $path

Any ideas?

Kangaroo
  • 105
  • 1
  • 1
  • 5

2 Answers2

21

Take a look at Select-String. It will allow you to find the entire line that contains what you are looking for. Then you can update the line.

This is a sample file

apple = yummy
bananna = yummy
pear = awful
grapes = divine

Say I want to replace the line containing "pear". First get the line:

$line = Get-Content c:\temp\test.txt | Select-String pear | Select-Object -ExpandProperty Line

Now we just read in the content and replace the line with our line:

$content = Get-Content c:\temp\test.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:\temp\test.txt

Confirm the changes

Get-Content C:\temp\test.txt
apple = yummy
bananna = yummy
pear = amazing
grapes = divine

Note that if you are working with XML, which it looks like you might be you can open the document as an XML document and simply replace the attribute. Without seeing a sample of your source file its hard to tell.

StephenP
  • 3,895
  • 18
  • 18
  • Thank you for showing me this I didn't know know that existed. Could you maybe help me out with an example? How could I use that to find my line by only knowing `Setting amount = ` but then replace the entire line with something else? – Kangaroo Dec 04 '17 at 13:38
  • Updated the answer with an example for reading in from text, finding the line, replacing it, and saving – StephenP Dec 05 '17 at 03:38
11

Thanks for the code. Works well but just want to add that this goes bad if the string is not found at all. It will replace every line in your file. This fixed up my issue with that by checking for null:

$line = Get-Content c:\temp\test.txt | Select-String pear | Select-Object -ExpandProperty Line

if ($line -eq $null) {
"String Not Found"
exit
} else {
$content = Get-Content c:\temp\test.txt
$content | ForEach-Object {$_ -replace $line,"pear = amazing"} | Set-Content c:\temp\test.txt

}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Bryan Kerwin
  • 111
  • 1
  • 2
  • This is a very good point which helped me out alot. If your not careful you can loose everything that way. – Nathan Nov 19 '20 at 14:56