Powershell 搜索字符串并替换文件中的整行

Powershell 搜索字符串并替换文件中的整行,powershell,Powershell,我想在文件中搜索字符串,并用命令返回的值替换整行。但由于某些原因,脚本不会更新文件中的值 例如:在文件中搜索$FileName,并将该行替换为$FileName=truncate_20190523.log from$key变量,该变量的值派生自$NewFile变量 $LogName = "Test.Log" $FullPath = "\\etldev\logs" $NewFile = Get-ChildItem -Path '\\etldev\logs\truncate_*' | Sort-

我想在文件中搜索字符串,并用命令返回的值替换整行。但由于某些原因,脚本不会更新文件中的值

例如:在文件中搜索$FileName,并将该行替换为$FileName=truncate_20190523.log from$key变量,该变量的值派生自$NewFile变量

$LogName = "Test.Log"

$FullPath = "\\etldev\logs"

$NewFile = Get-ChildItem -Path '\\etldev\logs\truncate_*' | Sort-Object LastWriteTime -Descending | Select-Object -First 1 | Select-Object -ExpandProperty Name

$Key = "`$FileName`=$NewFile"

$Line = Get-Content -Path $FullPath\$LogName | Select-String `$FileName` | Select-Object -ExpandProperty Line

(Get-Content -Path $FullPath\$LogName -Raw).Replace('$Line', $Key)| Set-Content -Path $FullPath\$LogName

看看您的$Line变量。里面应该有整个日志文件。 试着这样做:

$Content = Get-Content -Path $Path
$Line = $Content | Select-String -Pattern "Pattern" | Select-Object -ExpandProperty Line
$Index = $Content.IndexOf($Line) 
$Content[$Index]= "Replaced"
$Content | Out-File -FilePath $Path -Force

(获取内容'input.txt')-替换('.'+[regex]::Escape($FileName)+'.'),$Key |设置内容'output.txt'
@Ansgar:谢谢。我尝试了regex函数,它用输入值替换了整个文件,这不是我想要的。它必须只替换与搜索字符串匹配的行。我发布的代码应将包含
$FileName
值的行替换为
$Key
值,并保留所有其他内容不变。如果你得到了不同的结果,你没有运行我发布的代码。也许我应该用更好的方式解释。我想用$Key中的值替换包含名称“$FileName”的行。下面是运行脚本前后test.log文件的内容。前面:$FileName=truncate_20190522.log后面:$FileName=truncate_20190523.logAh,我明白了。您希望搜索字符串“$FileName”,而不是变量的值
$FileName
<代码>(获取内容“input.txt”)-替换(“^\$FileName.*”),$Key |设置内容“output.txt”。谢谢。我根据您的建议修复了我的代码,并将您的代码添加到其中,它起了作用。当它解决您的问题时,请接受它作为答案。