chocolatey / package-validator

Windows service to validate packages conform to package standards
Apache License 2.0
31 stars 29 forks source link

Requirement: Validate PowerShell #107

Open ferventcoder opened 8 years ago

ferventcoder commented 8 years ago

http://stackoverflow.com/a/10813842/18475

https://msdn.microsoft.com/en-us/library/system.management.automation.psparser(v=vs.85).aspx

http://blogs.microsoft.co.il/scriptfanatic/2009/09/07/parsing-powershell-scripts/

While we shouldn't use this, it's important to note that it is there if we need it: POSH v3+ has AST support - https://msdn.microsoft.com/en-us/library/system.management.automation.language(v=vs.85).aspx

ferventcoder commented 8 years ago

This will also help us with #1

ferventcoder commented 8 years ago

Whoa - it's actually super simple. From http://powershell.org/wp/forums/topic/how-to-check-syntax-of-scripts-automatically/#post-12834 :

function Test-PowerShellSyntax
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Path
    )

    $contents = Get-Content -Path $Path -ErrorAction Stop

    $errors = $null
    $null = [System.Management.Automation.PSParser]::Tokenize($contents, [ref]$errors)

    return ($errors.Count -eq 0)
}
ferventcoder commented 8 years ago

Valid powershell

Collection<PSParseError> errors = null;
var tokens = PSParser.Tokenize(contents, out errors);

return errors.Count() == 0;