Home > Software design >  How to replace PHP variable with powershell?
How to replace PHP variable with powershell?

Time:01-24

I have to replace my PHP variable with powershell. The variable is $env = "TEST" but with powershell I want to replace it to $env = "TEST" because of using Azure Releases. Currently I am having a sript like this:

(Get-Content -Path 'C:\MyProject\MyBuildOutputs\connect.php') | 
Foreach-Object { $_ -replace '$env = "TEST"', '$env = "PROD"' } | 
Set-Content -Path 'C:\MyProject\MyBuildOutputs\connect.php' -Force

But unfortunately it doesn't work and I don't know why.

How do I do that?

CodePudding user response:

This happens because Powershell's -replace expects a regex pattern. $ has a special meaning in regular expressions, it is the end of line anchor. So the command is looking at pattern that's

 end of line, followed by env = "TEST"

To use dollar sign as a literal character, either escape it \$, or use the [regex] type accelereator to access escape() and let Powershell do the escaping. Like so,

$_ -replace [regex]::escape('$env = "TEST"'), '$env = "PROD"' 
  • Related