1

I am distributing several powershell scripts to various machines and want to make sure it is executable and does not contain any errors before uploading the new version to our distribution system.

How can I solve this with Gitlab .gitlab-ci.yml?

1
  • as i am not really familiar with powershell, but at least with gitlab ci - maybe gitlab.com/guided-explorations/… is a good resource and starting point for you ;) Commented Feb 12, 2021 at 19:49

2 Answers 2

3

I have found a solution for my issue. This step in the build process checks the Powershell script and aborts the build if there are any errors.

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Not sure if this is what you are looking for or if it applies at all to .yml files as I'm not familiar with them, but for powershell script files you can use the creation of [scriptblock] to check for syntax and other compile errors. You can create a function with this code and pass in powershell script files to it which can take the code, try to compile it, and return any exceptions encountered.

# $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
}

Output

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

I also recommend looking into Pester for testing scripts. If you are unfamiliar it is a testing and mocking framework for Powershell code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.