package-validator icon indicating copy to clipboard operation
package-validator copied to clipboard

Requirement: Validate PowerShell

Open ferventcoder opened this issue 10 years ago • 3 comments

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 avatar Jan 23 '16 12:01 ferventcoder

This will also help us with #1

ferventcoder avatar Jan 23 '16 12:01 ferventcoder

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 avatar Jan 23 '16 13:01 ferventcoder

Valid powershell

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

return errors.Count() == 0;

ferventcoder avatar Jan 25 '16 17:01 ferventcoder