There are countless other ways to replace strings in a text file with PowerShell. PS C:\> Get-Content -path C:\ReplaceDemo.txt Voila! PS C:\> ((Get-Content -path C:\ReplaceDemo.txt -Raw) -replace 'brown','white') | Set-Content -Path C:\ReplaceDemo.txt After Get-Content reads the file and passes the string to the replace operator, PowerShell then hands off that new string to Set-Content, which takes that string as pipeline input and overwrites the existing file. In this instance, we're overwriting the entire file with the string output that the replace operator returned.īelow, I've wrapped the whole previous operation in parentheses to ensure PowerShell doesn't try to pass any output prematurely to Set-Content. Unlike Add-Content, Set-Content overwrites a file. Now that we have the code to find and replace the string we're after, it's now time to modify the file itself. The quick white fox jumped over the lazy dog PS> (Get-Content -path C:\ReplaceDemo.txt -Raw) -replace 'brown','white' This is required to ensure Get-Content is complete before attempting any replace operation on its output. Notice that the Get-Content command execution is in parentheses. The replace operator returns the new string. This operator can be used against any string.īelow you can see how it's being used in-line against the output of Get-Content. The replace operator takes as arguments the string to find and the string to replace it with. To make that happen, we'll use PowerShell's replace operator. We're not actually changing the file yet. Next, we'll have to figure out a way to find and replace the string "brown" in memory. The quick brown fox jumped over the lazy dog PS C:\> Get-Content -path C:\ReplaceDemo.txt -Raw To perform a find/replace in a text file, it's much easier to return the contents via single string. You can see that Get-Content read the file and returned the contents to the console, but it did this by returning an array.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
June 2023
Categories |