PowerShell QuickTip: Preparsing Scripts to Check for Syntax Errors

There are a number scenarios where you need to update a script to add a minor feature or fix a bug but you can’t really run the script to test your changes.  Perhaps the script is destructive and you’d have to comment out a bunch of script to test and then remember to uncomment the code.  Or perhaps the script can only be run on a production server and won’t run on your dev PC.  Wouldn’t be nice if there were a way to at least have PowerShell try to parse the script after your updates and report parse/syntax errors.  In a previous post I discussed how to do this when dealing with a script full of just functions (ie no directly executing script).  This approach doesn’t work if your scripts contain script at the top level.  However there is another way that will at least tell you if there is a problem or not:

# Contents of file TestScript.ps1
param($path, [switch]$verbose)

if ($verbose) {
    $VerbosePreference = ‘Continue’

trap { Write-Warning $_; $false; continue }
& `
    $contents = get-content $path
    $contents = [string]::Join([Environment]::NewLine, $contents)
    Write-Verbose "Parsed without errors"

Note that this doesn’t give useful error information such as the actual line of script that is bad but at least you will know if there is a problem or not.

Many thanks to Karl Prosser of PowerAnalyzer fame for giving me the pointer to the $ExecutionContext.InvokeCommand.NewScriptBlock method.

Update: Fixed some script problems pointed out by Shay.  Thanks!

This entry was posted in PowerShell. Bookmark the permalink.

3 Responses to PowerShell QuickTip: Preparsing Scripts to Check for Syntax Errors

  1. Shay says:

    I saved the code as Parse-Script.ps1 and executed:
    C:\\Scripts\\Parse-Script.ps1 -path C:\\Scripts\\Parse-Script.ps1
    I get an error:
    Exception calling "NewScriptBlock" with "1" argument(s): "Unexpected token \’if\’ in expression or statement."At line:1 char:47+ $ExecutionContext.InvokeCommand.NewScriptBlock( <<<< (gc C:\\Scripts\\Parse-Script.ps1))
    The error is not consistent. Some scripts get parsed with errors and some fails (scripts with if or switch statments).
    —–Shay Levi$cript Fanatichttp://scriptolog.blogspot.com 

  2. Keith says:

    Shay, thanks for helping me QA this.  🙂  Try the update and see if it is more accurate.  BTW it is unfortunate I can\’t better positon information on parse errors.

  3. Shay says:

    Thank you, Works perfect!
    Shay Levi$cript Fanatichttp://scriptolog.blogspot.com 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s