仅替换文本文件中的一行

Ney*_*eyt 1 powershell

这是我要修改的文本文件:

Sometext
2016
Sometext
Sometext
6
Sometext

我要修改的两个值是第2行和第5行(索引1和4),它们是当前年份和当前月份.

所以我做了这个PowerShell脚本:

$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
Run Code Online (Sandbox Code Playgroud)

但显然,这条线

(Get-Content $file).Replace($oldMonth, $month) | Set-Content $file
Run Code Online (Sandbox Code Playgroud)

将替换我文件中的所有"6"与当前月份(当我写这些行时为7),但我只想要替换第5行,而不是第2行.

Mar*_*ndl 5

您不需要用新值替换旧值,而是可以通过索引选择适当的行并只替换值:

$content = Get-Content $file
$content[1] = (Get-Date).Year
$content[4] = (Get-Date).Month
$content | Set-Content $file
Run Code Online (Sandbox Code Playgroud)

请注意,Set-Contentcmdlet可能会更改文件编码.