Aero Chocolate
Aero Chocolate

Reputation: 1497

Replacing value on one line in a text file

I am currently working on editing one line of a text file. When I try to overwrite the text file, I only get one line back in the text file. I am trying to call the function with

modifyconfig "test" "100"

config.txt:

check=0
test=1

modifyConfig() function:

Function modifyConfig ([string]$key, [int]$value){
    $path = "D:\RenameScript\config.txt"

    ((Get-Content $path) | ForEach-Object {
        Write-Host $_
        # If '=' is found, check key
        if ($_.Contains("=")){
            # If key matches, replace old value with new value and break out of loop
            $pos = $_.IndexOf("=")
            $checkKey = $_.Substring(0, $pos)
            if ($checkKey -eq $key){
                $oldValue = $_.Substring($pos+1)
                Write-Host 'Key: ' $checkKey
                Write-Host 'Old Value: ' $oldValue
                $_.replace($oldValue,$value)
                Write-Host "Result:" $_
            }
        } else {
            # Do nothing
        }
    }) | Set-Content ($path)
}

The result I receive in my config.txt:

test=100

I am missing "check=0".

What have I missed?

Upvotes: 4

Views: 10820

Answers (2)

Adarsha
Adarsha

Reputation: 2377

or a one liner.. (not exactly pin pointed answer, but to the question title)

(get-content $influxconf | foreach-object {$_ -replace "# auth-enabled = false" , "auth-enabled = true" }) | Set-Content $influxconf

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

$_.replace($oldValue,$value) in your innermost conditional replaces $oldValue with $value and then prints the modified string, but you don't have code printing non-matching strings. Because of that only the modified string are written back to $path.

Replace the line

# Do nothing

with

$_

and also add an else branch with a $_ to the inner conditional.

Or you could assign $_ to another variable and modify your code like this:

Foreach-Object {
    $line = $_
    if ($line -like "*=*") {
        $arr = $line -split "=", 2
        if ($arr[0].Trim() -eq $key) {
            $arr[1] = $value
            $line = $arr -join "="
        }
    }
    $line
}

Upvotes: 5

Related Questions