powershellvalidationpowershell-cmdletsyntax-checking

How to do full syntax check of PowerShell script file using the PowerShell cmdlet


I'm writing a console application to validate the PowerShell script syntax. My request is to validate the PowerShell script without executing the script. I found this below PowerShell command which can perform the syntax check without executing the scripts.

Get-Command -syntax 'D:\powershell\deleteDemoFile.ps1'

However, I found that it does not do a complete syntax check. For example a variable is used in the PowerShell without declaring or their is typos in the (Function, if, ForEach, etc.) such syntax error is not captured by the above command.

Below is the sample code of the PowerShell script file (.\deleteDemoFile.ps1) Notice in the below code the spelling of (if, Function) is wrong and a variable '$log_dir' is used but is not declared.

When I run the PowerShell Command Get-Command -syntax 'D:\powershell\deleteDemoFile.ps1' the command does not throw any syntax error.

Write-Host "Hello, World!"

ifTypo(-not (test-path -path $log_dir )) {
   new-item -itemtype directory -path $log_dir
}


FunctionTypo log {
   Param ([string]$log_string)
   write-host $log_string
   add-content $log_file -value $log_string
}

log("Deleting a demo txt file")

# PowerShell -WhatIf safety parameter
Clear-Host
Get-Childitem D:\powershell\SomeFile\demo.txt -Recurse | Remove-Item

So I was wondering.

Is there any other Command which can perform full syntax check?

Here is the reference of the PowerShell command: https://stackoverflow.com/a/55337824/3725706


Solution

  • Note that the purpose of Get-Command's -Syntax switch is to show a command's syntax diagram, i.e. to show its parameters and their types, i.e. how to invoke it.

    Since discovering this information for scripts requires parsing them, as a side effect you would indeed detect syntax errors[1] (the Get-Command call then fails and reports the specific syntax error encountered).

    However, your example script does not contain syntax errors: while it won't do what you want when executed, it is syntactically valid:


    The Invoke-ScriptAnalyzer cmdlet (part of the PSScriptAnalyzer module you can install with Install-Module PSScriptAnalyzer) suggested by iRon, which is also used in the PowerShell extension for Visual Studio Code for design-time analysis, may be able to point out potential additional problems, but in the case at hand it wouldn't (it only warns against Write-Host use in your script).


    Note:


    [1] In effect, Get-Command -Syntax is indirectly a convenient shortcut to calling the official PowerShell parser in order to find syntax errors, which requires more effort - see this answer.