PowerShell script to find and replace text in a file

Powershell Script to Find and Replace Text in a File

To find and replace a particular word throughout a file on multiple computers is as laborious as one can imagine. However, with the help of the following PowerShell script, one can easily find a particular word and replace it with a word of choice.
 
To do so, provide the file path, the text to find, and the text to be replaced as parameters and run the script. 

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

 




    • Related Articles

    • How to find unused Exchange Online mailboxes

      What are unused Exchange Online mailboxes and how to identify them? Unused Exchange Online mailboxes are user mailboxes which are currently not being used by their users. There are 3 ways in which we can identify if a mailbox is unused or not. They ...
    • Generate an Activity Report for Microsoft 365 Groups and Teams

      Introduction The activity reports available for Microsoft 365 groups and Teams can be beneficial for administrators in an organization. Microsoft 365 teams group activity reports provide insight into group activities, group workloads, group counts, ...
    • Display Events with a particular Text

      Administrators often have to stifle through Windows logs to troubleshoot problems with their systems or applications. However, manually going through heaps of system log information to find out the root cause of an event can be quite laborious.   ...
    • Clear Contents of a File

      Temporary files can take up considerable space in a database and eventually slow down computers. Administrators can use the following PowerShell script to completely clear the contents of files remotely. If you want to delete the entire text file ...
    • Powershell Script to Delete Files Older than X days

      Files and folders can accumulate over time and take up considerable space in the database or hard drives and end up slowing the computer considerably. However, deleting them manually isn't quite scalable. This is where PowerShell scripts can be of ...