我正在编写一个控制台应用程序来验证 PowerShell 脚本语法。
我的请求是验证 PowerShell 脚本而不执行该脚本。我在下面的 PowerShell 命令中发现了这个命令,它可以在不执行脚本的情况下执行语法检查。
Get-Command -syntax 'D:\powershell\deleteDemoFile.ps1'
但是,我发现它没有进行完整的语法检查。
例如,在 PowerShell 中使用变量而无需声明
或者他们的拼写错误(Function、if、ForEach 等)
上述命令未捕获此类语法错误。
以下是 PowerShell 脚本文件 (.\deleteDemoFile.ps1) 的示例代码
请注意,下面的代码中 (if, Function) 的拼写错误,并且使用了变量“$log_dir”但未声明。
当我运行 PowerShell 命令时Get-Command -syntax 'D:\powershell\deleteDemoFile.ps1'
该命令不会引发任何语法错误。
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
所以我想知道。
- 此 PowerShell 命令进行语法检查的效率如何?
- 它是否仅验证 PowerShell cmdlet、函数和别名的语法?
- 此命令与哪个版本的 PowerShell 脚本兼容?
还有其他命令可以执行完整的语法检查吗?
以下是 PowerShell 命令的参考:https://stackoverflow.com/a/55337824/3725706 https://stackoverflow.com/a/55337824/3725706
请注意,目的是Get-Command https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-command's -Syntax
switch 是显示命令的语法图 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Command_Syntax,即显示其参数及其类型,即如何调用它.
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).
然而,你的示例脚本确实not包含syntax errors: 虽然它不会做你想做的事执行时, it is 语法上有效的:
-
ifTypo
and FunctionTypo
被解释为命令名称,不是拼写错误的keywords.
- 因此,您只会看到问题执行时,当尝试调用command(cmdlet、函数、脚本、别名、可执行文件)命名
ifTypo
,例如,是制成的。
-
看概念图about_解析 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Parsing帮助主题以获取有关以下内容的信息PowerShell 的两种基本解析模式,argument模式(如 shell)和表达模式(如编程语言).
The Invoke-ScriptAnalyzer https://learn.microsoft.com/en-us/powershell/module/psscriptanalyzer/invoke-scriptanalyzercmdlet(的一部分PSScriptAnalyzer
您可以安装的模块Install-Module PSScriptAnalyzer
) 建议来自iRon https://stackoverflow.com/users/1701026/iron,它也用在 Visual Studio Code 的 PowerShell 扩展中进行设计时分析,may能够指出潜在的其他问题,但在手头的情况下它不会(它只是警告Write-Host
在您的脚本中使用)。
Note:
-
PowerShell 的两种解析模式总是相当漂亮宽容的语法,一般来说,你能做的只有这么多static用动态语言进行分析。
-
现有功能无法检测脚本的问题;一个可能的解决方案是询问新规则用于标记潜在的关键字拼写错误被添加到Invoke-ScriptAnalyzer
, by 在项目的 GitHub 存储库中打开一个问题 https://github.com/PowerShell/PSScriptAnalyzer/issues/new/choose,但请注意,这些规则最终是猜测,因为看起来像拼写错误的关键字可能是合法的命令名称。
[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 https://stackoverflow.com/a/43214144/45375.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)