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.
- How efficient is this PowerShell command in order to do a syntax check?
- Does it only validate the syntax of PowerShell cmdlets, functions, and aliases?
- Up to which version of PowerShell script this command is compatible?
Is there any other Command which can perform full syntax check?
Here is the reference of the PowerShell command: https://mcmap.net/q/714220/-how-can-i-automatically-syntax-check-a-powershell-script-file
Invoke-ScriptAnalyzer
? – HoehneGet-Command
doesn't validate anything - it only discovers things – CatiGet-Command -Syntax
is to show the syntax diagram (usage information), but to do so the script must be parsed, so as a side effect syntax errors do surface. – Sarazen