Powershell scripting replace of variable value within text file like tnsnames.ora where the text for replace is unknown

Viewed 41

I'm trying to write into my powershell script the ability to insert a hostname into a file like tnsnames.ora.

The file I am working with has a default value in that field, and I can't rely on what that value will be, so a simple replace of that text string won't work.

I need to be able to check the file for instances of "HOST = abcdefg123" (where abcdefg123 is the server's name place holder) and replace that string with my server's hostname.

The trick seems to be taking this file and locating abcdefg123 so that I can replace it. It can appear multiple times in the file, and the HOST variable may not be the first item on the line.

Here is a sample tnanames.ora file for a SAP database:

A01.WORLD=   (DESCRIPTION =
    (SDU = 32768)
    (ADDRESS_LIST =
        (ADDRESS =
          (COMMUNITY = SAP.WORLD)
          (PROTOCOL = TCP)
          (HOST = columbus)
          (PORT = 1529)
       )
    (CONNECT_DATA =
       (SID = A01)
       (GLOBAL_NAME = A01.WORLD)
    )   )

TEC.WORLD=   (DESCRIPTION =
    (ADDRESS_LIST =
        (ADDRESS =
          (COMMUNITY = TEC.WORLD)
          (PROTOCOL = TCP)
          (HOST = columbus)
          (PORT = 1521)
        )
    )
    (CONNECT_DATA =
       (SID = TEC)
        (GLOBAL_NAME = TEC.WORLD)
        ) )

I was trying to work to adapt the following code (I found in another post) to work but have not been successful so far:

Get-Content file.txt | Where-Object {$_.length -gt 0} | Where-Object {!$_.StartsWith("#")} | ForEach-Object {
   
    $var = $_.Split('=',2).Trim()
    New-Variable -Scope Script -Name $var[0] -Value $var[1]
    
}

The Split by = character would not work right especially where I found there was more than one = argument on the same line (the quoted sample does not show this but the file I was working with does). (Obviously I corrected for the file name. I also tried addition where-object elements to eliminage lines starting with ')' for example, but I don't think that was very useful.

1 Answers

Use a regex-based -replace operation:

(Get-Content -Raw file.txt) -replace '(?<=\(HOST = )[^)]+', 'newServer'

For an explanation of the regex and the ability to experiment with it, see this regex101.com page.

Related