Aer*_*ate 4 string powershell replace text-files
我目前正在编辑文本文件的一行。当我尝试覆盖文本文件时,我只在文本文件中恢复一行。我正在尝试调用该函数
modifyconfig "test" "100"
Run Code Online (Sandbox Code Playgroud)
config.txt:
检查=0 测试=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)
}
Run Code Online (Sandbox Code Playgroud)
我收到的结果是config.txt:
测试=100
我缺少“检查=0”。
我错过了什么?
$_.replace($oldValue,$value)在最里面的条件替换$oldValue为$value然后打印修改后的字符串,但是您没有打印不匹配字符串的代码。因此,只有修改后的字符串才会写回$path.
更换线路
# Do nothing
Run Code Online (Sandbox Code Playgroud)
和
$_
Run Code Online (Sandbox Code Playgroud)
并向内部条件添加一个else带有 a 的分支。$_
或者您可以分配$_给另一个变量并修改您的代码,如下所示:
Foreach-Object {
$line = $_
if ($line -like "*=*") {
$arr = $line -split "=", 2
if ($arr[0].Trim() -eq $key) {
$arr[1] = $value
$line = $arr -join "="
}
}
$line
}
Run Code Online (Sandbox Code Playgroud)