📎 AI Summary:
The thread discusses a user seeking help to replace the word "Hello" in numerous text files with "Hello+filename" using PowerShell. While Neemobeer provides a script solution, the user encounters issues with the script not functioning as intended and later reports that the modified files display unexpected characters ("ÿþ%") when opened with their program, though they appear correct in standard text editors. Overall, the conversation reflects troubleshooting efforts to achieve accurate text replacement without file content corruption.

marcoswebot

New Member
Joined
Apr 8, 2019
Messages
4
Thread Author #1
Hello. I have several hundred text files in a folder. I would like to replace the text "Hello" present in every files with the actual "filename".
How to do that? Can I use a Script or PowerShell?

Thank you!
 

Solution
With PowerShell

Code:
$SearchDirectory = "C:\path\to\directory"

$Files = Get-ChildItem -Path $SearchDirectory -File

foreach($File in $Files)
{
    $FileData = Get-Content $File.FullName
    $ReplaceString = "Hello"
    $ReplaceData = "Hello+$($File.Name)"

    $NewFileData = $FileData.Replace($ReplaceString,$ReplaceData)
   
    Out-File -FilePath $File.FullName -InputObject $NewFileData -Force
}

Neemobeer

Windows Forum Team
Staff member
Joined
Jul 4, 2015
Messages
8,995
With PowerShell

Code:
$SearchDirectory = "C:\path\to\directory"

$Files = Get-ChildItem -Path $SearchDirectory -File

foreach($File in $Files)
{
    $FileData = Get-Content $File.FullName
    $ReplaceString = "Hello"
    $ReplaceData = "Hello+$($File.Name)"

    $NewFileData = $FileData.Replace($ReplaceString,$ReplaceData)
   
    Out-File -FilePath $File.FullName -InputObject $NewFileData -Force
}
 

Solution

marcoswebot

New Member
Joined
Apr 8, 2019
Messages
4
Thread Author #3
With PowerShell

Code:
$SearchDirectory = "C:\path\to\directory"

$Files = Get-ChildItem -Path $SearchDirectory -File

foreach($File in $Files)
{
    $FileData = Get-Content $File.FullName
    $ReplaceString = "Hello"
    $ReplaceData = $File.Name

    $NewFileData = $FileData.Replace($ReplaceString,$ReplaceData)
   
    Out-File -FilePath $File.FullName -InputObject $NewFileData -Force
}

Thanks Neemobeer, but this did not work for me.
I did not explain very good. I try again:

What I need to do is to change the TEXT "Hello" with the TEXT "Hello+filename"
 

Neemobeer

Windows Forum Team
Staff member
Joined
Jul 4, 2015
Messages
8,995
You need to change the path mentioned in the first line
$SearchDirectory = "C:\path\to\directory"

Otherwise post the error "this is not working" doesn't tell me much.
 

marcoswebot

New Member
Joined
Apr 8, 2019
Messages
4
Thread Author #7
Neemobeer, thanks again for your help.
It works but somehow when I open the file with my program i get this: ÿþ% instead of the full text.
If I open the program with text editor it works but with my special text editor no :-/ Do you know which could be the reason?

Thanks a lot :-D