Gitlab CI/CD 验证 powershell 脚本

Gitlab CI/CD validate powershell script

我正在将几个 powershell 脚本分发到不同的机器,并希望在将新版本上传到我们的分发系统之前确保它是可执行的并且不包含任何错误。

如何用 Gitlab 解决这个问题.gitlab-ci.yml

不确定这是否是您正在寻找的,或者它是否适用于 .yml 文件,因为我不熟悉它们,但是对于 powershell 脚本文件,您可以使用 [scriptblock] 的创建来检查语法和其他编译错误。您可以使用此代码创建一个函数并将 powershell 脚本文件传递给它,它可以获取代码,尝试编译它,return 遇到任何异常。

# $code = Get-Content -Raw $file  
$code = @"
 while {
    write-host "no condition set on while "
 }
 do {
    Write-Host "no condition set on unitl "
 } until ()
"@

try {
    [ScriptBlock]::Create($code)
}
catch {
    $_.Exception.innerexception.errors
}

输出

Extent ErrorId                            Message                                    IncompleteInput
------ -------                            -------                                    ---------------
       MissingOpenParenthesisAfterKeyword Missing opening '(' after keyword 'while'.           False
       MissingExpressionAfterKeyword      Missing expression after 'until' in loop.            False

我还建议查看 Pester 以测试脚本。如果您不熟悉它,它是一个用于 Powershell 代码的测试和模拟框架

我找到了解决问题的方法。构建过程中的此步骤会检查 Powershell 脚本并在出现任何错误时中止构建。

gitlab-ci.yml

stages:
  - validate

validate_script:
  stage: validate
  image:
    name: "mcr.microsoft.com/powershell:ubuntu-20.04"
  script:
    - pwsh -File validate.ps1
  tags:
  - docker

validate.ps1

Write-Host "Install PSScriptAnalyzer"
Install-Module PSScriptAnalyzer -Scope CurrentUser -Confirm:$False -Force

Write-Host "Check mypowershell.ps1"
$result = Invoke-ScriptAnalyzer -Path 'src/mypowershell.ps1'
if ($result.Length -gt 0) {
    Write-Host "Script Error"
    Write-Host ($result | Format-Table | Out-String)
    exit 1;
}