如何验证powershell条件语法?

un-*_*ieH 3 powershell static-analysis

PowerShell 中有条件语法检查器吗?此代码将跳过条件

if ($templList -ne $null -and $templList.items.Length > 0) {
  $templID=$templList.items[0].id
  write-host $templList.items
}
Run Code Online (Sandbox Code Playgroud)

因为“-gt”被“>”替代。

mkl*_*nt0 5

严格来说,您正在寻找语义检查器,前提是您的代码在语法上是正确的

这里的问题是,虽然代码在形式上是正确的,但它并没有达到您的预期目的

PSScriptAnalyzer (PSSA) 是PowerShell 的linter,它集成到Visual Studio CodePowerShell 扩展中。

它会捕获您的问题,并发出以下消息:

您的意思是使用重定向运算符“>”吗?
PowerShell 中的比较运算符为“-gt”(大于)或“-ge”(大于或等于)。


在 Visual Studio 代码中使用:

  • 安装PowerShell 扩展

  • 安装后,打开脚本进行编辑,您将看到> 0带下划线的部分,并将鼠标悬停在其上,该消息将显示为工具提示。

  • 您可以在“问题”视图(Ctrl-Shift-M或者通过菜单View > Problems)中查看当前文件的所有消息,顺便说一句,这将向您显示 PSSA 发现您的代码片段存在其他潜在问题。

  • 要配置要应用的规则(要警告哪些潜在问题),请>PowerShell: Select PSScriptAnalyzer Rules从命令选项板使用。

    • 规则名称,例如PSAvoidGlobalVars,大多是不言自明的;规则文档描述了它们(没有PS前缀);还有一个最佳实践主题

    • 重要的

      • 选中/取消选中(或按下Enter)感兴趣的规则后,请务必按下Enter顶部Confirm的菜单项,否则您的更改将不会生效。

      • 从 v2019.11.0 开始,这些选择不会保留(仅在当前会话中记住) - 请参阅此 GitHub 问题

请注意,PSSA还提供PowerShell 代码的自动(重新)格式化Alt-Shift-F或者通过命令选项板>Format Document)。


单机使用:

  • PSScriptAnalyzer从 PowerShell Gallery安装模块;例如:

  • 将脚本的路径传递给Invoke-ScriptAnalyzercmdlet 以执行 linting。

使用您的代码,您将看到以下输出(已获得名为 的脚本pg.ps1):


RuleName                            Severity     ScriptName Line  Message
--------                            --------     ---------- ----  -------
PSPossibleIncorrectUsageOfRedirecti Warning      pg.ps1     1     Did you mean to use the redirection operator '>'? The
onOperator                                                        comparison operators in PowerShell are '-gt' (greater than)
                                                                  or '-ge' (greater or equal).
PSPossibleIncorrectComparisonWithNu Warning      pg.ps1     1     $null should be on the left side of equality comparisons.
ll
PSUseDeclaredVarsMoreThanAssignment Warning      pg.ps1     2     The variable 'templID' is assigned but never used.
s
PSAvoidUsingWriteHost               Warning      pg.ps1     3     File 'pg.ps1' uses Write-Host. Avoid using Write-Host
                                                                  because it might not work in all hosts, does not work when
                                                                  there is no host, and (prior to PS 5.0) cannot be
                                                                  suppressed, captured, or redirected. Instead, use
                                                                  Write-Output, Write-Verbose, or Write-Information.
Run Code Online (Sandbox Code Playgroud)