Open In App

How to find and replace the content from the file or string using PowerShell

Improve
Improve
Like Article
Like
Save
Share
Report

PowerShell is a versatile utility that can manage files and folders in various ways. It gives you access to the system’s files and directories and lets you create, copy, delete, move, renames, and examine them. Several useful PowerShell cmdlets can read, write, and replace data in files. In this article, we will see how we can find and replace the content from the file and string.

Searching Content from the String and File

Firstly we will look at how to search the content from the string and file. For that select-string cmdlet is there which helps in finding the pattern from the string or file 

Features of select-string cmdlet:

  • Select-String cmdlet uses the regular expression to find the string pattern in strings or files.
  • Select-String is based on a line of text and searches pattern through each line and stops after the first matches.
  • It returns the object if the pattern matches found else the null object returns.

Syntax of Select-String:

[-Pattern] <String[]>
[-Path] <String[]>

PowerShell Code 1 (Without Function):

search.ps

$filePath = "C:\Users\HP\OneDrive\Desktop\demo.txt"
$selectString = "the good day with rohit sahu"
$check = select-string -pattern $selectString -path $filePath
if($check -eq $null){
   Write-output "String Not Found"
}
else{
   Write-output "String Found"
}

 

PowerShell Code 2 (With Function):

search.ps

function search-string{
   $filePath1 = "C:\Users\HP\OneDrive\Desktop\demo.txt"
   $selectString1 = "hello Rohit sahu"
   
   $chck = select-string -Path $filepath1 -Pattern $selectString1
   
   if($chck -eq $null){
       Write-output "String Not Found"
   }   
   else{
       Write-output "String Found"
   }
}
search-string

Replace the Content from the String or File

For the Replace the content we have some cmdlet Get-Content and Set-Content this cmdlet helps in fetching and replacing the content from the file or string, with the help of this cmdlet we can read and replace any kind of content inside the file whether it’s a complicated or single word. Powershell has the capability to replace the content about anything.

Syntax of Get-Content:

Get-Content -Path $filePath

This will return the content from the file 

((Get-Content -path $filePath ) -replace ‘old_Word’,’new_Word’) | Set-Content -Path $filePath

PowerShell Code:

replace.ps

$content = ((Get-Content -Path $filePath) -replace ‘how are you i’,’I know that you’ | Set-Content -Path $filePath)

$content1 = Get-Content -Path $filePath
Write-output $content1

We have taken the below output screenshot before running the code.

 

 

The below screenshot is taken after executing the PowerShell code.

 

 


Last Updated : 07 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads