Contrary to “normal” languages like C# or Java, Powershell is not a compiled language, but rather an interpreted one. This means that instead of using a compiler, the Powershell Scripting Runtime Environment reads and executes the code line-by-line during runtime.
That has well known advantages -for example, you can change code on the spot- and disadvantages -e.g. performance. But one major disadvantage is that there are no compiler errors. That means that if you forget to close a parenthesis or a bracket, nothing works. It’s the silliest of mistakes but still crashes everything.
With Powershell being used in non-interactive environments, like Azure Functions, it’s becoming all the more important to guard against such errors.
Fortunately, there is a solution for this. Microsoft has published the PSScriptAnalyzer module (link) which includes the Invoke-ScriptAnalyzer (link) command. Running this against your code, you get a list of warnings and errors:
The best things is, you can include this in your CI/CD pipelines, e.g. in Azure Devops or Github.
So here’s an example of an Azure Devops pipeline task that checks for ParseErrors (meaning, the script is not readable) and stops the build in case such an error is found:
#
# Source: DotJim blog (http://dandraka.com)
# Jim Andrakakis, October 2024
#
- task: PowerShell@2
displayName: Check for Powershell parsing errors
inputs:
targetType: 'inline'
errorActionPreference: 'stop'
pwsh: true
script: |
Install-Module -Name PSScriptAnalyzer -Scope CurrentUser -Force
Write-Host 'Performing code analysis using Microsoft Invoke-ScriptAnalyzer'
$findings = Invoke-ScriptAnalyzer -Path '$(System.DefaultWorkingDirectory)' -Recurse -Severity ParseError,Error
$findings | Format-List
if (($findings | Where-Object { $_.Severity -eq 'ParseError' }).Count -gt 0) { Write-Warning "Parse error(s) were found, review analyser results."; exit 1 }
Enjoy 😊
