我目前正在编辑文本文件的一行。当我尝试覆盖文本文件时,文本文件中只返回一行。我正在尝试用
调用该函数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)
}
我在 config.txt
中收到的结果:
test=100
我缺少“check=0”。
我错过了什么?
最佳答案
$_.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
}
关于string - 替换文本文件中一行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099177/