替换文本文件中一行的值

时间:2013-06-14 00:04:02

标签: string powershell replace text-files

我目前正在编辑一行文本文件。当我尝试覆盖文本文件时,我只在文本文件中返回一行。我试图用

调用该函数
modifyconfig "test" "100"

config.txt

check=0
test=1

modifyConfig()功能:

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)
}

我在config.txt收到的结果:

test=100

我错过了“check = 0”。

我错过了什么?

2 个答案:

答案 0 :(得分:4)

最内层条件中的

$_.replace($oldValue,$value)$oldValue替换$value,然后打印修改后的字符串,但是没有代码打印不匹配的字符串。因此,只有修改后的字符串才会写回$path

替换

# Do nothing

$_

并将else分支与$_添加到内部条件。

或者您可以将$_分配给另一个变量并修改您的代码:

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

答案 1 :(得分:1)

或一个班轮..(不完全针对答案,但问题标题)

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