0

I need to find in a file specific line and add some data at the end of the line, something like this:

function AddSomeData($file, $key, $value) 
{
    $content = Get-Content $file
    if ($content -match "I work very") 
    {
        $content- add at the end $value
        Set-Content $file     
    }
}

AddSomeData "settings.conf" "I work very" " hard"

As a result - file with changed line: I work very hard. How to do that ?

2 Answers 2

1

Here's how I'ld do it:

Function AddSomeData(){
    param(
        [Parameter(Mandatory=$true)][String]$file,
        [Parameter(Mandatory=$true)][String]$key,
        [Parameter(Mandatory=$true)][String]$value
    )
    $content = get-content $file | ForEach-Object { 
        IF($_ -eq $key){"$key $value"} 
        ELSE {$_}
    }
    $content | Set-Content $file
}

Then just call the Function with:

AddSomeData settings.conf 'I work very' 'hard'
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a regular expression to search and replace on each line and then output to a new file. For example:

get-content "settings.conf" | foreach-object {
  $_ -replace 'I work very$','$0 hard'
} | out-file "settings2.conf"

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.