Powershell script to replace characters within multiple files

I have created a Powershell script that will replace a character string with another string, this works file along as only one file is in the directory.

This is the script I am using

#Example of PowerShell replacing text
Clear-host
$Location = "C:\Users\luketr\Desktop\test\*.txt"
$Change = Get-Content $Location
$Change | ForEach-Object {$_ -Replace "'THIRD',", ""} | Set-Content $Location
$Change | ForEach-Object {$_ -Replace "'SECOND',", ""} | Set-Content $Location
$Change | ForEach-Object {$_ -Replace "'FOURTH',", ""} | Set-Content $Location

If I have more than one file in the directory the files are merged.

I have attached the files I am wanting the place the word, SECOND, THIRD and FOURTH in the separate files.

Thanks

Luke
bacotim0.20986.txt
bacotim0.21008.txt
bacotim0.21033.txt
Luke Toulmin-RotheAsked:
Who is Participating?
 
oBdACommented:
Powershell 2? From 2009? Seriously?
Get-ChildItem -Path "C:\Users\luketr\Desktop\test" -Filter "*.txt" | ForEach-Object {
	([System.IO.File]::ReadAllText($_)) -replace "'(SECOND|THIRD|FOURTH)',", "" | Set-Content -Path $_
}

Open in new window

0
 
oBdACommented:
Get-ChildItem -Path "C:\Users\luketr\Desktop\test" -Filter "*.txt" | ForEach-Object {
	(Get-Content -Path $_ -Raw -Encoding ASCII) -replace "'(SECOND|THIRD|FOURTH)',", "" | Set-Content -Path $_
}

Open in new window

0
 
Luke Toulmin-RotheAuthor Commented:
Thanks when I run this I get the following error.

Get-Content : A parameter cannot be found that matches parameter name 'Raw'.
At C:\Users\luketr\Desktop\Test\find and replace.ps1:2 char:28
+     (Get-Content -Path $_ -Raw <<<<  -Encoding ASCII) -replace "'(SECOND|THIRD|FOURTH)',", "" | Set-Content -Path $_
    + CategoryInfo          : InvalidArgument: (:) [Get-Content], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
0
 
Luke Toulmin-RotheAuthor Commented:
Excellent thank you very much.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.