Created
September 10, 2025 09:25
-
-
Save fahadysf/67342e359f334e58841484ee9f8767a4 to your computer and use it in GitHub Desktop.
Powershell-String-Replacement.ps1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Set the paths for your files | |
| $replacementListFile = "C:\temp\replace.txt" | |
| $targetFile = "C:\temp\target.xml" | |
| # Read the contents of the replacement list file | |
| $replacementList = Get-Content -Path $replacementListFile | |
| # Read the content of the target file into a single string | |
| $content = Get-Content -Path $targetFile -Raw | |
| # Loop through each line in the replacement list file | |
| foreach ($line in $replacementList) { | |
| # Skip empty lines or lines that start with a comment character (#) | |
| if (-not [string]::IsNullOrWhiteSpace($line) -and -not $line.StartsWith("#")) { | |
| # Split the line into the string to replace and the replacement string | |
| # using the first comma as the delimiter | |
| $parts = $line.Split([char]',' , 2) | |
| # Check if the line has at least two parts | |
| if ($parts.Count -eq 2) { | |
| $stringToReplace = $parts[0] | |
| $replacementString = $parts[1] | |
| # Perform the replacement using the -replace operator | |
| # The `-replace` operator is a regular expression-based replacement. | |
| # To perform a literal string replacement, escape special regex characters. | |
| $content = $content -replace [regex]::Escape($stringToReplace), $replacementString | |
| } | |
| } | |
| } | |
| # Write the modified content back to the target file | |
| Set-Content -Path $targetFile -Value $content |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment