Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automatically syntax check a powershell script file?

I want to write a unit-test for some code which generates a powershell script and then check that the script has valid syntax.

What's a good way to do this without actually executing the script?

A .NET code solution is ideal, but a command line solution that I could use by launching an external process would be good enough.

like image 461
Tim Lovell-Smith Avatar asked Apr 04 '17 17:04

Tim Lovell-Smith


2 Answers

I stumbled onto Get-Command -syntax 'script.ps1' and found it concise and useful.

ETA from the comment below: This gives a detailed syntax error report, if any; otherwise it shows the calling syntax (parameter list) of the script.

like image 169
Willem M. Avatar answered Sep 19 '22 21:09

Willem M.


You could run your code through the Parser and observe if it raises any errors:

# Empty collection for errors
$Errors = @()

# Define input script
$inputScript = 'Do-Something -Param 1,2,3,'

[void][System.Management.Automation.Language.Parser]::ParseInput($inputScript,[ref]$null,[ref]$Errors)

if($Errors.Count -gt 0){
    Write-Warning 'Errors found'
}

This could easily be turned into a simple function:

function Test-Syntax
{
    [CmdletBinding(DefaultParameterSetName='File')]
    param(
        [Parameter(Mandatory=$true, ParameterSetName='File', Position = 0)]
        [string]$Path, 

        [Parameter(Mandatory=$true, ParameterSetName='String', Position = 0)]
        [string]$Code
    )

    $Errors = @()
    if($PSCmdlet.ParameterSetName -eq 'String'){
        [void][System.Management.Automation.Language.Parser]::ParseInput($Code,[ref]$null,[ref]$Errors)
    } else {
        [void][System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$null,[ref]$Errors)
    }

    return [bool]($Errors.Count -lt 1)
}

Then use like:

if(Test-Syntax C:\path\to\script.ps1){
    Write-Host 'Script looks good!'
}
like image 40
Mathias R. Jessen Avatar answered Sep 20 '22 21:09

Mathias R. Jessen