Search code examples
powershelldate-rangepowershell-cmdlet

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


A nice tough one for you all. I'm trying to find and replace a given string in a bunch of files. The files have a date stamp in the file name i.e. YYYY_MM_DD_file.txt

I wish to search and replace within a date range for these files and then replace a string I define, I cannot use date modified as the date range, I must rely on the stamp in the filename.

So far I set my date range in WPF text fields:

$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  

I then get child items using the $files1 array I have created as a search mask for the files in the date range and find all matches. Store this in a variable and replace the string $filename with the new string $Newfilenamereal.

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

write-host $Matches1

However I cannot work out how to overwrite what has been found and replaced in the $Matches1 variable to the original files. I have tried set-content, however this will simply either erase everything I have in the date stamped files or cannot understand the $files1 array as a file path.

So my question to you lovely people is how do I write what I have replaced in the environment to the actual files?


Solution

  • Just retrieve the file content using the Get-Content cmdlet and replace the string. Finally write it back using the Set-Content cmdlet:

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