Reputation: 83
I want to search for a string in a file and replace the entire line with a value returned from a command. But for some reason the script does not update the value in the file.
Ex: Search for $FileName in the file and replace that line with the value $FileName=truncate_20190523.log from $key variable which has the value derived from the $NewFile variable.
$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
Upvotes: 0
Views: 93
Reputation: 2434
Take a look at your $Line variable. There should be the whole log file in it. Try it like that:
$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
Upvotes: 1