SoFunction
Updated on 2025-04-09

Powershell tips: Find errors in scripts

It is never easy to find out syntax errors in scripts, but you can filter them like this:

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

In this script, you can quickly scan a directory or PS files in the entire computer to find out the syntax errors in them.

The following example will find the syntax errors of all PS scripts in the user directory:

Copy the codeThe code is as follows:

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

Supports all PS versions