Powershell Script to Find and Replace in a File

To Find a text and replace it with a desired text in a File . Supply file path , the text to find and the text to be replaced as parameter.

Script

<#
.SYNOPSIS
This script can be used to find a text and replace it with a desired text in a file.
.DESCRIPTION
This script can be used to find a text and replace it with a desired text in a file.
.EXAMPLE
C:\PS> C:\Script\Find_and_Replace.ps1 C:\Script\test.txt powershell windowspowershell
Finds ‘powershell’ in C:\Script\test.txt and replaces it with ‘windows powershell’.
#>

param([String] $file,[String] $source , [String] $replace)
#Get the entire file content.

$content = Get-Content $file
$content
Write-Host
#Replace the source word with the replace word.

$content = $content -creplace $source,$replace
$content
#set the file content.

$content | Set-Content $file

 

Output
Replace

Leave a Reply