如何验证 powershell 条件语法?

How to validate powershell conditional syntax?

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

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

因为 '-gt' 被替换为 '>'。

严格来说,您正在寻找 语义 检查器,因为您的代码 语法正确

这里的问题是虽然代码在形式上是正确的,但它没有按照您打算它做的那样做。

PSScriptAnalyzer (PSSA) is a linter for PowerShell, and it is integrated into the PowerShell extension for Visual Studio Code.

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

Did you mean to use the redirection operator '>'?
The comparison operators in PowerShell are '-gt' (greater than) or '-ge' (greater or equal).


用于Visual Studio代码:

  • 安装 PowerShell extension.

  • 安装后,打开您的脚本进行编辑,您会看到 > 0 部分带有下划线,悬停在它上面会显示消息作为工具提示。

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

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

    • 规则名称,例如PSAvoidGlobalVars,大多是不言自明的; rules documentation describes them (without the PS prefix); and there's also a best practices topic.

    • 重要

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

      • 自 v2019.11.0 起,这些选择 不会保留 (仅在当前会话中记住)- 请参阅 this GitHub issue

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


单机使用:

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

  • 将脚本的路径传递给 Invoke-ScriptAnalyzer cmdlet 以执行 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.