Question:
Here is the text file I want to modify:
1 2 3 4 5 6 |
Sometext 2016 Sometext Sometext 6 Sometext |
The two values I want to modify are on line 2 and 5 (Index 1 and 4), which are the current year and the current month.
So I did this PowerShell script:
1 2 3 4 5 6 7 8 9 10 11 12 |
$file = "$PSScriptRoot\myFile.txt" $date = Get-Date $year = $date.Year $month = $date.Month $oldYear = Get-Content $file | Select -Index 1 $oldMonth = Get-Content $file | Select -Index 4 (Get-Content $file).Replace($oldYear, $year) | Set-Content $file (Get-Content $file).Replace($oldMonth, $month) | Set-Content $file |
But obviously, this line
1 2 |
(Get-Content $file).Replace($oldMonth, $month) | Set-Content $file |
will replace all the “6” in my file with the current month (which is 7 at the time I’m writing these lines), but I only want the 5th line to be replaced, not the 2nd.
Answer:
You don’t need replace old value with new value, you can instead select the appropriate line by index and just replace the values:
1 2 3 4 5 |
$content = Get-Content $file $content[1] = (Get-Date).Year $content[4] = (Get-Date).Month $content | Set-Content $file |
Be aware that the Set-Content
cmdlet may change the file encoding.