Extract and replace content in http link from a text file

Hi everyone, I am new in powershell and I have created the following script which it extract what’s between http:// and the next /, transform it and then replace the intial match:

$configFileName = “myfile”
$octopusEnvironment = “Newenvironment”
$config = Get-Content $configFileName

$newConfig = $config | % { $_ -replace “http://www.site.de”, “http://site.de.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site.com.tr”, “http://site.com.tr.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site.fr”, “http://site.fr.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site.pl”, “http://site.pl.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site-1.be”, “http://site-1.be.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site-1.nl”, “http://site-1.nl.$octopusEnvironment” }
$newConfig = $newConfig | % { $_ -replace “http://www.site.it”, “http://site.it.$octopusEnvironment” }

$newConfig | Set-Content $configFileName

I’m trying to make it better, maybe using regex or something else but not using hard coded text.

Could anyone please help me with this ?

Thanks

Please show as sample of the file you are using for this…

Get-Content $configFileName

… you should be able to split as substring via GC without much work, though RegEx is still an option, but may be overkill for what you are after here.

Hello and thanks for the help but I have resolved it:

$fileName = “myfile”
$newEnvironment = “NewEnvironment”

$pattern = "(?<=http://)www.([^/ ]+)(?!.$newEnvironment)"
$replacement = "`$1.$newEnvironment"

(Get-Content $path) -replace $pattern,$replacement | Set-Content $path

Regards