You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本构建ASP.NET Core项目并配置Azure NuGet源凭据

PowerShell脚本:拉取代码并构建ASP.NET Core Web API

下面是一套完整的PowerShell脚本方案,涵盖拉取develop分支代码、配置Azure NuGet源凭据、更新包并构建的全流程:

一、配置Azure NuGet源凭据

针对Azure Artifacts NuGet源,有两种常用的凭据配置方式,按需选择:

1. 使用Azure DevOps个人访问令牌(PAT)

先在Azure DevOps中创建PAT,权限需包含Packaging (Read)。脚本中配置方式如下:

# 定义NuGet源参数
$nugetSourceName = "AzureArtifactsFeed"
$nugetSourceUrl = "https://pkgs.dev.azure.com/你的组织名/_packaging/你的Feed名/nuget/v3/index.json"
# 建议从环境变量读取PAT,避免明文硬编码
$patToken = $env:AZURE_DEVOPS_PAT

# 用dotnet CLI配置源并设置凭据(用户名可任意填写,比如"azdevops")
dotnet nuget add source $nugetSourceUrl --name $nugetSourceName --username azdevops --password $patToken --store-password-in-clear-text

2. 使用Azure AD身份验证(适用于已登录Azure的环境)

如果脚本运行环境已通过Azure CLI登录,可自动获取访问令牌:

# 若未登录,先执行交互式登录(或使用托管身份登录)
# az login
# az login --identity

# 获取Azure Artifacts的访问令牌
$accessToken = az account get-access-token --resource "https://pkgs.dev.azure.com" --query accessToken -o tsv

# 配置NuGet源
dotnet nuget add source $nugetSourceUrl --name $nugetSourceName --username az --password $accessToken --store-password-in-clear-text

二、批量拉取develop分支最新代码

假设你有多个解决方案路径,可通过列表批量处理:

# 定义所有解决方案的根路径
$solutionRoots = @(
    "D:\Projects\OrderAPI",
    "D:\Projects\PaymentAPI",
    "D:\Projects\UserAPI"
)

foreach ($root in $solutionRoots) {
    Write-Host "===== 处理项目: $root ====="
    Set-Location $root

    # 切换到develop分支并拉取最新代码
    git checkout develop
    git pull origin develop
}

三、更新NuGet包并构建项目

在拉取代码后,执行依赖恢复与构建:

foreach ($root in $solutionRoots) {
    Set-Location $root

    # 恢复依赖(同时从Azure源和官方NuGet源拉取)
    dotnet restore --source $nugetSourceUrl --source https://api.nuget.org/v3/index.json

    # 构建Release版本
    dotnet build --configuration Release --no-restore
}

关键安全提示

  • 绝对不要将PAT明文写入脚本,优先通过环境变量或PowerShell凭据管理器存储:
    # 交互式获取凭据(可选)
    $cred = Get-Credential -Message "输入Azure DevOps PAT(用户名任意)"
    $patToken = $cred.GetNetworkCredential().Password
    
  • 若在Azure DevOps Pipeline中运行,可直接使用内置的NuGetAuthenticate任务,无需手动配置凭据。

内容的提问来源于stack exchange,提问作者cksanjose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:00:00