Finding Errors in Scripts

by Sep 17, 2014

All PowerShell Versions

It’s never been easier to find scripts with syntax errors in them. Just use this filter:

filter Test-SyntaxError
   $text = Get-Content -Path $_.FullName
   if ($text.Length -gt 0)
      $err = $null
      $null = [System.Management.Automation.PSParser]::Tokenize($text, [ref] $err)
      if ($err) { $_ }

With it, you can quickly scan folders or even entire computers and list all PowerShell files that have syntax errors in them.

This would search and find all PowerShell scripts in your user profile and list only those that have syntax errors:

PS> dir $home -Filter *.ps1 -Recurse -Exclude *.ps1xml | Test-SyntaxError

Twitter This Tip! ReTweet this Tip!