PowerShell实现每次签出后自动递增JSON文件指定字段数值
PowerShell脚本:签出后自动递增Azure参数文件VMName序号
功能说明
- 读取指定的Azure部署参数JSON文件
- 自动提取
VMName字段值末尾的数字序号,执行+1操作 - 不改动JSON其他配置项,更新后回写原文件
- 支持绑定Git post-checkout钩子,签出完成后自动运行
完整脚本
把下面的代码保存为Update-VMName.ps1,修改开头的文件路径为你本地的参数文件实际路径:
# 替换为你的azuredeploy.parameters.json实际路径 $parameterFile = "D:\your-repo\azuredeploy.parameters.json" # 读取并解析JSON $deployParam = Get-Content $parameterFile -Raw -Encoding UTF8 | ConvertFrom-Json $currentVMName = $deployParam.parameters.VMName.value # 正则匹配前缀+末尾数字的格式 if ($currentVMName -match '^(.*\D)(\d+)$') { $namePrefix = $matches[1] $seqNumber = [int]$matches[2] # 保留原序号的前导零位数 $newSeq = $seqNumber + 1 $newVMName = $namePrefix + $newSeq.ToString("D" + $matches[2].Length) # 更新值并回写文件 $deployParam.parameters.VMName.value = $newVMName $deployParam | ConvertTo-Json -Depth 10 | Set-Content $parameterFile -Encoding UTF8 Write-Host "VMName更新完成:$currentVMName → $newVMName" } else { Write-Error "VMName格式错误,当前值为$currentVMName,未检测到末尾数字序号" exit 1 }
配置Git签出后自动执行
- 进入你的Git仓库下的
.git/hooks目录 - 新建名为
post-checkout的文件(无文件后缀) - 在文件中写入以下内容,替换为你刚才保存的ps1脚本实际路径:
#!/bin/sh powershell.exe -ExecutionPolicy Bypass -NoProfile -File "D:\scripts\Update-VMName.ps1"
- 保存后给该文件添加可执行权限即可,后续每次执行
git checkout切换分支完成后,脚本会自动运行更新VMName序号。
适配说明:脚本会自动适配带前导零的序号格式,比如原VMName为
AEU-EHSSAS009,更新后会是AEU-EHSSAS010,不会丢失前导零;如果前缀中包含数字也不会干扰匹配,只会取最末尾连续的数字段做递增。
内容的提问来源于stack exchange,提问作者Anurag Poria
相关产品推荐
相关产品推荐

