按文件名查找和替换给定日期范围内文件中的字符串

Find and replace strings in files in a given date range by filename

对你们所有人来说都是一个很好的艰难的。我试图在一堆文件中查找并替换给定的字符串。这些文件的文件名中有日期戳,即 YYYY_MM_DD_file.txt

我想在一个日期范围内搜索并替换这些文件,然后替换我定义的字符串,我不能使用修改日期作为日期范围,我必须依赖文件名中的戳记。

到目前为止,我在 WPF 文本字段中设置了我的日期范围:

$Filename = $Filenamebox.text
$startdate = [datetime] $startdatetext.text
$enddate = [datetime] $enddatetext.Text
$NewFilenamereal = $Newfilename.Text

$array = 
   do {
   $startdate.ToString('yyyy_MM_dd*')
   $startdate = $startdate.AddDays(1)
  }

until ($startdate -gt [datetime] $enddate)


$files1 = $array | foreach-object {"C:\Users\michael.lawton\Desktop\KGB\Test folder$_"}

write-host $files1  

然后我使用我创建的 $files1 数组获取子项目作为日期范围内文件的搜索掩码并找到所有匹配项。将其存储在变量中并将字符串 $filename 替换为新字符串 $Newfilenamereal.

$Matches1 = get-childitem $files1 | select-string $Filename | foreach-object    {$_ -replace $Filename,$Newfilenamereal} | out-string

write-host $Matches1

但是我不知道如何将 $Matches1 变量中找到和替换的内容覆盖到原始文件中。我试过 set-content,但这只会删除我在带日期戳的文件中的所有内容,或者无法将 $files1 数组理解为文件路径。

所以我想问你们可爱的人,我如何将我在环境中替换的内容写入实际文件?

只需使用 Get-Content cmdlet 检索文件内容并替换字符串。最后使用 Set-Content cmdlet 将其写回:

Get-ChildItem $files1 | ForEach-Object {
    ($_ | Get-Content -Raw) -replace $Filename,$Newfilenamereal | 
        Set-Content -Path $_.FullName -Encoding UTF8
}