Last active
September 28, 2024 23:16
-
-
Save Calvindd2f/9fde7eb1ac88a1aa307ad8befe99d435 to your computer and use it in GitHub Desktop.
Function for en masse replacing rotated secrets in a series of text files.
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
| function Replace-Secret { | |
| <# | |
| .SYNOPSIS | |
| Replaces a specified string (such as a secret) in a file with a new string. | |
| .DESCRIPTION | |
| This function reads a file, replaces all occurrences of a specified old string with a new string, and writes the changes back to the file. | |
| .PARAMETER FilePath | |
| The path to the file where the replacement should occur. | |
| .PARAMETER OldString | |
| The string to be replaced. | |
| .PARAMETER NewString | |
| The string that will replace the old string. | |
| .EXAMPLE | |
| $filePath = "$PROFILE" | |
| $oldSecret = "this-is-a-test-credential-located-in-the-content-of-`$profile" | |
| $newSecret = "test-credential_newsecret-example" | |
| Replace-Secret -FilePath $filePath -OldString $oldSecret -NewString $newSecret | |
| .EXAMPLE | |
| Further capability can be obtained by scanning an entire folder tree and essentially 'cat'-ign each file and regex replacing the old secret with the newly created secret or even a null value. | |
| $files=gci -r -File; | |
| foreach ($f in $files){ | |
| Replace-Secret -OldString $OldString -NewString $NewString -FilePath $f | |
| }; | |
| if($NewString -notcontains 'null') | |
| { | |
| # A call or function to write this secret to Bitwarden or something similar . | |
| } | |
| #> | |
| [CmdletBinding()] | |
| param ( | |
| [Parameter(Mandatory=$true)] | |
| [string]$FilePath, | |
| [Parameter(Mandatory=$true)] | |
| [string]$OldString, | |
| [Parameter(Mandatory=$true)] | |
| [string]$NewString | |
| ) | |
| begin { | |
| if (-not (Test-Path -Path $FilePath)) { | |
| throw "File not found: $FilePath" | |
| } | |
| $content = Get-Content -Path $FilePath -Raw | |
| } | |
| process { | |
| try { | |
| $escapedOldString = [regex]::Escape($OldString) | |
| $pattern = "(?<=(?:'|\`"|=))$escapedOldString(?=(?:'|\`"))" | |
| $newContent = $content -replace $pattern, $NewString | |
| if ($newContent -eq $content) { | |
| [console]::WriteLine("No occurrences of the specified string were found in the file.") | |
| } else { | |
| Set-Content -Path $FilePath -Value $newContent | |
| [console]::WriteLine("Replacement complete in file: $FilePath") | |
| } | |
| } | |
| catch { | |
| throw "An error occurred: $($_.Exception.Message)" | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Output