PowerShell スクリプトを使用してパイプラインをカスタマイズする

Azure DevOps Services | Azure DevOps Server 2022 - Azure DevOps Server 2019 | TFS 2018

Note

Microsoft Visual Studio Team Foundation Server 2018 以前のバージョンでは、名前付けに次の違いがあります。

  • ビルドとリリースのためのパイプラインはビルドとリリースのためのパイプラインです。そしてそれらは定義と呼ばれます。
  • 実行ビルドと呼ばれます。
  • サービス接続サービスエンドポイントと呼ばれます。
  • ステージ環境と呼ばれます
  • ジョブは(フェーズと呼ばれます。

コードのコンパイルとテストの基本の先に進む準備ができたら、PowerShell スクリプトを使用して、チームのビジネス ロジックをビルド パイプラインに追加します。 Windows PowerShell は、Windows ビルド エージェントで実行できます。 PowerShell Core は、あらゆるプラットフォームで動作します。

PowerShell スクリプトを追加する

PowerShell Core を含める構文は、Windows PowerShell の構文とは少々異なります。

  1. PowerShell スクリプトをリポジトリにプッシュしてください。

  2. pwsh または powershell ステップを追加してください。 pwsh キーワードは、PowerShell Core の PowerShell タスクのショートカットです。 powershell キーワードは、PowerShell タスクのもう 1 つのショートカットです。

# for PowerShell Core
steps:
- pwsh: ./my-script.ps1

# for Windows PowerShell
steps:
- powershell: .\my-script.ps1

Windows PowerShell スクリプトは、Windows ビルド エージェントで実行できます。

  1. スクリプトをリポジトリにプッシュしてください。

  2. PowerShell ビルド タスクを追加してください。

    Add task

    Add PowerShell task

  3. ビルド タスクを実行する場所にドラッグしてください。

  4. プログラムの名前を指定してください。

PowerShell スクリプトの例: バージョン アセンブリ

アセンブリのバージョンを設定するスクリプトの例を次に示します。 スクリプトが正常に実行されるようにするには、4 つのピリオド (例: $(BuildDefinitionName)_$(Year:yyyy).$(Month).$(DayOfMonth)$(Rev:.r)) の形式を使用するようにビルド番号を更新する必要があります。 ビルド番号は、実行番号とも呼ばれます。

name プロパティを使用して、YAML パイプライン内でビルド番号をカスタマイズすることができます。

name: $(BuildDefinitionName)_$(Year:yyyy).$(Month).$(DayOfMonth)$(Rev:.r)

pool:
  vmImage: windows-latest

steps:
- pwsh: echo $(Build.BuildNumber) //output updated build number
# If found use it to version the assemblies.
#
# For example, if the 'Build number format' build pipeline parameter 
# $(BuildDefinitionName)_$(Year:yyyy).$(Month).$(DayOfMonth)$(Rev:.r)
# then your build numbers come out like this:
# "Build HelloWorld_2013.07.19.1"
# This script would then apply version 2013.07.19.1 to your assemblies.
	
# Enable -Verbose option
[CmdletBinding()]
	
# Regular expression pattern to find the version in the build number 
# and then apply it to the assemblies
$VersionRegex = "\d+\.\d+\.\d+\.\d+"
	
# If this script is not running on a build server, remind user to 
# set environment variables so that this script can be debugged
if(-not ($Env:BUILD_SOURCESDIRECTORY -and $Env:BUILD_BUILDNUMBER))
{
	Write-Error "You must set the following environment variables"
	Write-Error "to test this script interactively."
	Write-Host '$Env:BUILD_SOURCESDIRECTORY - For example, enter something like:'
	Write-Host '$Env:BUILD_SOURCESDIRECTORY = "C:\code\FabrikamTFVC\HelloWorld"'
	Write-Host '$Env:BUILD_BUILDNUMBER - For example, enter something like:'
	Write-Host '$Env:BUILD_BUILDNUMBER = "Build HelloWorld_0000.00.00.0"'
	exit 1
}
	
# Make sure path to source code directory is available
if (-not $Env:BUILD_SOURCESDIRECTORY)
{
	Write-Error ("BUILD_SOURCESDIRECTORY environment variable is missing.")
	exit 1
}
elseif (-not (Test-Path $Env:BUILD_SOURCESDIRECTORY))
{
	Write-Error "BUILD_SOURCESDIRECTORY does not exist: $Env:BUILD_SOURCESDIRECTORY"
	exit 1
}
Write-Verbose "BUILD_SOURCESDIRECTORY: $Env:BUILD_SOURCESDIRECTORY"
	
# Make sure there is a build number
if (-not $Env:BUILD_BUILDNUMBER)
{
	Write-Error ("BUILD_BUILDNUMBER environment variable is missing.")
	exit 1
}
Write-Verbose "BUILD_BUILDNUMBER: $Env:BUILD_BUILDNUMBER"
	
# Get and validate the version data
$VersionData = [regex]::matches($Env:BUILD_BUILDNUMBER,$VersionRegex)
switch($VersionData.Count)
{
   0		
      { 
         Write-Error "Could not find version number data in BUILD_BUILDNUMBER."
         exit 1
      }
   1 {}
   default 
      { 
         Write-Warning "Found more than instance of version data in BUILD_BUILDNUMBER." 
         Write-Warning "Will assume first instance is version."
      }
}
$NewVersion = $VersionData[0]
Write-Verbose "Version: $NewVersion"
	
# Apply the version to the assembly property files
$files = gci $Env:BUILD_SOURCESDIRECTORY -recurse -include "*Properties*","My Project" | 
	?{ $_.PSIsContainer } | 
	foreach { gci -Path $_.FullName -Recurse -include AssemblyInfo.* }
if($files)
{
	Write-Verbose "Will apply $NewVersion to $($files.count) files."
	
	foreach ($file in $files) {
		$filecontent = Get-Content($file)
		attrib $file -r
		$filecontent -replace $VersionRegex, $NewVersion | Out-File $file
		Write-Verbose "$file.FullName - version applied"
	}
}
else
{
	Write-Warning "Found no files."
}

PowerShell スクリプトの例: REST API へのアクセス

この例では、SYSTEM_ACCESSTOKEN 変数を使用して、Azure Pipelines REST API にアクセスします。

YAML パイプライン内のスクリプトで $env:SYSTEM_ACCESSTOKEN を使用して、OAuth トークンにアクセスできます。

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=5.0"
              Write-Host "URL: $url"
              $pipeline = Invoke-RestMethod -Uri $url -Headers @{
                  Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
              }
              Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
  env:
     SYSTEM_ACCESSTOKEN: $(System.AccessToken)

よく寄せられる質問

スクリプトで使用できる変数は何ですか?

スクリプトで定義済みの変数を使用できます。 使用可能な変数とその使用方法の詳細については、「定義済みの変数を使用する」を参照してください。

後続のスクリプトやタスクで読み取ることができるように変数を設定するにはどうすればよいですか?

スクリプトでビルド変数を定義する方法の詳細については、スクリプトでのビルド変数の定義および変更に関する記事を参照してください。

スクリプトでリリース変数を定義する方法の詳細については、スクリプトでのリリース変数の定義および変更に関する記事を参照してください

ビルドはスクリプトのどのブランチを実行しますか?

ビルドでは、コードのアクティブなブランチが使用されます。 パイプライン実行で main ブランチが使用されている場合、スクリプトでも main ブランチが使用されます。

どのような種類のパラメーターを使用できますか?

名前付きパラメーターを使用できます。 スイッチ パラメーターなど、他の種類のパラメーターはサポートされていません。 スイッチ パラメーターを使用しようとすると、エラーが表示されます。

TFS をオンプレミスで使用していますが、これらの機能の一部が表示されません。 なぜでしょうか。

これらの機能の一部は Azure Pipelines でのみ使用でき、オンプレミスではまだ使用できません。 TFS の最新バージョンにアップグレードした場合は、一部の機能をオンプレミスで使用できます。