powshell-在teamcity上完成构建后发送钉钉通知

  1. 构建完成后获取构建job名称、构建id、归档文件地址
  2. 获取最新的3次git提交信息(如果是多个库,目前只拿了一个的commit msg)
  3. 发送钉钉通知

以后换可以扩展:

  1. 比如多个库的前几条commit msg,或者teamcity的changes
  2. teamcity如果是内网上,可以把构建文件上传到公网。

脚本内容

# 钉钉机器人配置
$token = "xxx"  # 替换为你的机器人实际token
 
# 1. 获取TeamCity环境变量
$serverUrl = if ($env:TEAMCITY_SERVER_URL) { $env:TEAMCITY_SERVER_URL } else { "http://192.168.0.116:8111" }
$buildTypeId = "%system.teamcity.buildType.id%"
$buildId = "%teamcity.build.id%"
$checkoutDir = $env:TEAMCITY_BUILD_CHECKOUTDIR

# 2. 设置默认值(如果环境变量不可用)
 
if (-not $buildId) { $buildId = "unknown" }
if (-not $checkoutDir) { $checkoutDir = Get-Location | Select-Object -ExpandProperty Path }

# 3. 动态获取Git仓库路径(支持多个仓库)
$gitRepoName = "chutian"  # 可根据不同Job修改此名称
$gitRepoPath = Join-Path -Path $checkoutDir -ChildPath $gitRepoName

Write-Host "服务器地址: $serverUrl"
Write-Host "构建类型ID: $buildTypeId"
Write-Host "构建ID: $buildId"
Write-Host "检出目录: $checkoutDir"
Write-Host "Git仓库路径: $gitRepoPath"

# 4. 获取Git提交信息(使用系统PATH中的git)
$commitMessages = "无提交信息"
try {
    if (Test-Path -Path $gitRepoPath) {
        $gitCommand = Get-Command git -ErrorAction SilentlyContinue
        if ($gitCommand) {
            # 执行git命令获取最近3条提交
            $processInfo = New-Object System.Diagnostics.ProcessStartInfo
            $processInfo.FileName = $gitCommand.Source
            $processInfo.Arguments = "-C `"$gitRepoPath`" log -3 --pretty=format:`" [%h] %s (%an)`""
            $processInfo.RedirectStandardOutput = $true
            $processInfo.RedirectStandardError = $true
            $processInfo.UseShellExecute = $false
            $processInfo.StandardOutputEncoding = [System.Text.Encoding]::UTF8
            $processInfo.StandardErrorEncoding = [System.Text.Encoding]::UTF8
            $processInfo.CreateNoWindow = $true
            
            $process = New-Object System.Diagnostics.Process
            $process.StartInfo = $processInfo
            $process.Start() | Out-Null
            $process.WaitForExit()
            
            $rawMessages = $process.StandardOutput.ReadToEnd().Trim()
            
            # 处理多行提交信息,确保在钉钉中正确换行显示
            if (-not [string]::IsNullOrEmpty($rawMessages)) {
                # 使用Markdown换行格式(两个空格加换行)
                $commitMessages = $rawMessages -replace "`r?`n", "  `n"
                Write-Host "获取到提交信息:`n$commitMessages"
            }
        } else {
            $commitMessages = "Git命令未找到"
            Write-Host "错误: Git命令未在PATH中找到"
        }
    } else {
        $commitMessages = "Git仓库路径不存在"
        Write-Host "警告: $gitRepoPath 不存在"
    }
} catch {
    $commitMessages = "获取提交信息失败: $($_.Exception.Message)"
    Write-Host "错误: $($_.Exception.Message)"
}

# 5. 构建Artifacts下载地址
$artifactsUrl = "$serverUrl/buildConfiguration/$buildTypeId/$($buildId)?buildTab=artifacts"
Write-Host "Artifacts URL: $artifactsUrl"

# 6. 获取项目名称和构建任务名称
$projectName = if ($env:TEAMCITY_PROJECT_NAME) { $env:TEAMCITY_PROJECT_NAME } else { "Chutian" }
$buildConfName = if ($env:TEAMCITY_BUILDCONF_NAME) { $env:TEAMCITY_BUILDCONF_NAME } else { "cli-backend打jar包" }

# 7. 构建消息内容
$messageText = @"
### 打包通知  
**项目名称**: $projectName  
**构建任务**: $buildConfName  
**构建ID**: $buildId  

**提交信息**:  
$commitMessages  

**安装包下载**:  
[点击下载 Artifacts]($artifactsUrl)  
"@

# 8. 构建请求URL
$webhookUrl = "https://oapi.dingtalk.com/robot/send?access_token=$token"

# 9. 构建消息体
$message = @{
    msgtype = "markdown"
    markdown = @{
        title = "打包通知"
        text = $messageText
    }
} | ConvertTo-Json -Depth 10

# 10. 发送请求
try {
    Write-Host "正在发送钉钉消息..."
    $response = Invoke-RestMethod -Uri $webhookUrl `
        -Method Post `
        -ContentType "application/json; charset=utf-8" `
        -Body $message
    
    if ($response.errcode -eq 0) {
        Write-Host "钉钉消息发送成功!" -ForegroundColor Green
    } else {
        Write-Host "发送失败: $($response.errmsg)" -ForegroundColor Red
    }
}
catch {
    Write-Host "请求异常: $_" -ForegroundColor Red
}

# 11. 打印最终消息内容
Write-Host "发送的消息内容:"
Write-Host $messageText

效果

image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容