I would use switch for that to examine the lines on-by-one, updating where needed
if ($isProduction) {
$commentOut = '*const basicPath*=*:3366/";'
$unComment = '*const basicPath*=*:5566/";'
}
else {
$commentOut = '*const basicPath*=*:5566/";'
$unComment = '*const basicPath*=*:3366/";'
}
$updated = switch -Wildcard -File 'api-requests.js' {
$commentOut { '// {0}' -f $_.TrimStart(" /") }
$unComment { $_.TrimStart(" /") }
default { $_ } # output this line unchanged
}
# save the updated file
$updated | Set-Content -Path 'api-requests.js'
Aha, I didn't know you ran the code by saving it as script and call that.
If you want it like that, you need to add a param() block to the script file like this:
param (
[switch]$isProduction
)
if ($isProduction) {
$commentOut = '*const basicPath*=*:3366/";'
$unComment = '*const basicPath*=*:5566/";'
}
else {
$commentOut = '*const basicPath*=*:5566/";'
$unComment = '*const basicPath*=*:3366/";'
}
$updated = switch -Wildcard -File 'D:\Test\api-requests.js' {
$commentOut { '// {0}' -f $_.TrimStart(" /") }
$unComment { $_.TrimStart(" /") }
default { $_ } # output this line unchanged
}
# save the updated file
$updated | Set-Content -Path 'D:\Test\api-requests.js'
Since -isProduction is merely a boolean, I made it into a [switch] parameter so you don't even need to specify $true or $false, just use the switch (for $true) or leave it out (for $false)
Let's assume this is the content of the current file:
some javascript code;
const basicPath = "http://serviceate01:5566/";
// const basicPath = "http://serviceate01:3366/";
more code;
Now when we can call the script with PowerShell 'D:\Test\test.ps1' -isProduction:$false or
simply leave out the switch so it will be interpreted as $false as in PowerShell 'D:\Test\test.ps1', the content is changed into:
some javascript code;
// const basicPath = "http://serviceate01:5566/";
const basicPath = "http://serviceate01:3366/";
more code;
By using the switch, with PowerShell 'D:\Test\test.ps1' -isProduction:$true, or simply PowerShell 'D:\Test\test.ps1' -isProduction,
the content of the file is changed again into:
some javascript code;
const basicPath = "http://serviceate01:5566/";
// const basicPath = "http://serviceate01:3366/";
more code;
P.S. It might be a good idea if you added another (optional) parameter to the script file called [string]$Path = 'api-requests.js' where you can specify the path and filename of the javascript file to update.