如何使用带布尔参数的PowerShell脚本切换JS文件指定行注释状态
PowerShell 脚本实现JS环境配置自动切换
针对需求实现的脚本可接收布尔型isProduction入参,自动处理当前工作目录下api-requests.js文件中的接口地址行注释切换,无需手动修改代码。
完整脚本代码
param( [Parameter(Mandatory = $true)] [bool]$isProduction ) # 拼接目标文件路径 $targetFilePath = Join-Path $PWD.Path "api-requests.js" # 校验文件存在性 if (-not (Test-Path $targetFilePath -PathType Leaf)) { throw "执行错误:当前工作目录下不存在 api-requests.js 文件,请确认路径后重试" } # 读取文件内容 $fileContent = Get-Content $targetFilePath -Encoding UTF8 # 定义两行配置的标准格式 $prodConfig = 'const basicPath = "http://serviceate01:5566/";' $testConfig = 'const basicPath = "http://serviceate01:3366/";' $commentedProd = "// $prodConfig" $commentedTest = "// $testConfig" # 逐行处理配置 $processedContent = foreach ($line in $fileContent) { # 清理行首空白、注释标记后做精准匹配 $coreContent = $line.TrimStart().TrimStart('/').TrimStart() switch ($coreContent) { $prodConfig { # 生产环境配置:isProduction为true时取消注释,否则加注释 if ($isProduction) { $prodConfig } else { $commentedProd } continue } $testConfig { # 测试环境配置:isProduction为true时加注释,否则取消注释 if ($isProduction) { $commentedTest } else { $testConfig } continue } default { $line } } } # 写回文件,使用UTF8编码适配前端文件 $processedContent | Set-Content $targetFilePath -Encoding UTF8
使用方法
将上述代码保存为.ps1后缀的PowerShell脚本文件(例如switch-api-env.ps1),在存放api-requests.js的目录下打开PowerShell终端,按需执行对应命令:
- 切换到生产环境(5566端口生效):
执行后文件中对应配置效果:.\switch-api-env.ps1 -isProduction $trueconst basicPath = "http://serviceate01:5566/"; // const basicPath = "http://serviceate01:3366/"; - 切换到测试环境(3366端口生效):
执行后文件中对应配置效果:.\switch-api-env.ps1 -isProduction $false// const basicPath = "http://serviceate01:5566/"; const basicPath = "http://serviceate01:3366/";
注意事项
- 脚本仅匹配
basicPath对应的两行端口配置,其余代码逻辑不会做任何修改 - 匹配逻辑自动兼容行首空白、已有注释标记的场景,不会出现重复加
//的问题 - 首次使用建议提前备份原
api-requests.js文件,避免误修改导致的问题
内容的提问来源于stack exchange,提问作者Maxim
相关产品推荐
相关产品推荐

