Need to know how to use PowerShell to read a text file and replace text? This is what we call the PowerShell Read-Text File.
Look no further! This blog post is for you. By the end of the post, I’ll show you a function I built to make your life much easier.
Replacing text in a file with PowerShell is three-step process.
- Reading the file
- Finding and replacing the string
- Writing changes to the file.
Reading the File
You’ll first need to read the file. Let’s first create one with the Set-Content
cmdlet so we have one to work with.
To read this file, you can use the Get-Content
command. You can read the file by providing a text file path to the Path
parameter as shown below.
Finding and Replacing the String
Now that we have the file’s content in memory in a string, we need to search and replace the string. One way to do that is to use the -replace
operator. This PowerShell operator finds a string and replaces it with another.
Using the example file contents, we can provide the search string foo with the replacement string bar which should make the file contents foo foo baz now.
Writing to the File
Now that we have the new file contents saved in $newContent
, we can now need to write this new content back to the file. One way to do that is to use the Set-Content
command.
The Set-Content
command replaces all contents of a file with assigning a new value.
Whenever you now read the C:\file.txt file with Get-Content
, you’ll see that it now contains the new content.
Dealing with Open File Handles
The steps you previously went through work….most of the time. However, you’ll find in the real world, it doesn’t always turn out that way.
You’ll find that you’ll occasionally have to deal with files that are either open PowerShell itself. This prevents you from writing the new contents back to the file.
To remedy this open file handle situation, I created a simple workflow that allows you to create a temporary text file on disk first with the new contents, remove the original file and then rename the temporary file.
Here’s an example of how it works:
Below is an example of a function I built called Find-InTextFile
which uses this approach combined with the ability to find (not replace) text in a file.
This function also uses the more powerful regular expression syntax to find strings as well. You’ll find that regular expressions will allow you to more flexible searching using special characters like single quotes, special characters and more.
You can also see below that I’m using a foreach loop to process multiple files at once. This comes in handy if you have a bunch of files to process.
Resources
For more information on the Set-Content
command check out Set-Content: The PowerShell Way to Write to a File or an alternative way to write contents to a file, the Out-File
command.
Source:
https://adamtheautomator.com/powershell-read-text-file/