Search code examples
azure-devopsyamlazure-pipelinesazure-pipelines-yaml

How can I have a variable for the last day of the current month


In my Yaml pipeline I need to use the last day of the current month as a variable but im not sure how to declare it

pool:
  vmImage: 'windows-latest'
variables:
  startOfMonth: $[format('{0:yyyy-MM}-01', pipeline.startTime)]
  endOfMonth:  $[format('{0:yyyy-MM}-01', pipeline.startTime).AddMonths(1).AddDays(-1)]

I tried here to get the day before the first of the nexrt month but it doesnt like me using methods here


Solution

  • As a workaround, you may use logging commands and PowerShell:

    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $pipelineDate = [DateTime]"$(system.pipelineStartTime)"
          $startOfMonth = $pipelineDate.ToString("yyyy-MM-01")
          $endOfMonth = ([DateTime]"$startOfMonth").AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd")
    
          Write-Host "$startOfMonth-$endOfMonth"
          Write-Host "##vso[task.setvariable variable=startOfMonth;]$startOfMonth"
          Write-Host "##vso[task.setvariable variable=endOfMonth;]$endOfMonth"
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
    
          Write-Host "$(startOfMonth)-$(endOfMonth)"