0

I'm trying to edit a text file from PowerHhell, following the refresh of a directory.

Trying to Get-Content from the target location where the source dbconnecthost is what we're searching for. We then want to replace with the target information and Set-Content. These variables are being pulled from another .ps1 file.

The below is what I'm attempting to use.

function ReplaceDBhost {
    Get-Content ("$TargetLocation\Data\config.txt") | Foreach-Object {
        $_ -replace ('^dbconnecthost=' + '$SourceDBConnectHost'), ('dbconnecthost=' + '$TargetDBConnectHost' )
    } | Set-Content  ("$TargetLocation\Data\config.txt")
} 

The problem is, I'm not getting any changes when I run this. Any help is greatly appreciated.

0

1 Answer 1

4

When you use single-quotes, that's called a string literal and does not support variable expansion. To correct this, you need to use double-quotes (or no quotes at all if your variable is a string and you're appending with +):

(Get-Content -Path "$TargetLocation\Data\config.txt") |
    ForEach-Object {
        $_ -replace "^dbconnecthost=$SourceDBConnectHost", "dbconnecthost=$TargetDBConnectHost"
    } |
    Set-Content -Path "$TargetLocation\Data\config.txt"

Although your regex can be improved using a lookaround:

"(?<=^dbconnecthost=)$SourceDBConnectHost", $TargetDBConnectHost

Shortened:

$path = @{Path = "$TargetLocation\Data\config.txt"}
$pattern = "(?<=^dbconnecthost=)$SourceDBConnectHost"
(Get-Content @path) -replace $pattern, $TargetDBConnectHost | Set-Content @path
Sign up to request clarification or add additional context in comments.

1 Comment

@LotPings good catch - or use -Raw with the multi-line regex option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.