Link to home
Start Free TrialLog in
Avatar of Luke Toulmin-Rothe
Luke Toulmin-Rothe

asked on

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
Avatar of oBdA
oBdA

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

Avatar of Luke Toulmin-Rothe

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Excellent thank you very much.