Creating collapsible sections in pipeline shell scripts

This is an old topic, but it’s still the first search result when I search DuckDuckGo for information about this, so I thought I’d provide an answer…

First, new versions of PowerShell support using backticks to print escape codes; see about Special Characters - PowerShell | Microsoft Docs. Unfortunately, it seems like that isn’t available on the Windows shared runners currently provided by GitLab. You can, however, use command substitutions to insert appropriate bytes in your strings manually.

Second, the PowerShell Get-Date function includes fractional sections when printing UNIX times, but GitLab doesn’t like that; it only wants whole seconds. So, you have to truncate the timestamps you put in your sections. Anyway, here’s an example of what works for me inside a .ps1 file:

function GetTime {
  $time = Get-Date -UFormat "%s"
  return $time.Substring(0, $time.IndexOf('.'))
}

# Install dependencies
Write-Output "$([char]27)[0Ksection_start:$(GetTime):install_chocolatey_dependencies[collapsed=true]$([char]13)$([char]27)[0KInstall Chocolatey Dependencies"
choco install -y packages.config --no-progress
Write-Output "$([char]27)[0Ksection_end:$(GetTime):install_chocolatey_dependencies$([char]13)$([char]27)[0K"

Hope that helps anybody else who is trying to figure out how to do this.