Search code examples
powershelltokenoctopus-deploy

How to search .token files in a folder and replace "__" in front and end of character via Powershell?


I would like to search thru files with .token files that have a string with the following pattern __[characters]__ and perform the following via PowerShell:

  • remove "__" (two underscores) in front of any character with an "#{"
  • remove "__" (two underscores) at the end of the same character and replace with "}"

For example:

__STAGE__
to
#{STAGE}

I am migrating RM token files to Octopus Deploy and need a clean up step via scripting.


Solution

  • In the most basic way and assuming there's no problem fitting a token file into memory:

    $TokenFiles = Get-ChildItem *.token
    
    foreach ($file in $TokenFiles) {
        $NewContent = Get-Content $file.FullName -Raw
        $NewContent = $NewContent -replace '__(.*?)__', '#{$1}'
        Set-Content $file.FullName -Value $NewContent
    }