gpt4 book ai didi

powershell - 如何验证powershell条件语法?

转载 作者:行者123 更新时间:2023-12-03 00:59:08 26 4
gpt4 key购买 nike

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

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

因为'-gt'被'>'取代。

最佳答案

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

这里的问题是,虽然代码在形式上是正确的,但它并没有按照您的意图去做。

PSScriptAnalyzer (PSSA) 是 linter用于 PowerShell , 并集成到 PowerShell extension对于 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带下划线的部分,将鼠标悬停在其上会将消息显示为工具提示。
  • 您可以在“问题” View (Ctrl-Shift-M 或通过菜单 View > Problems)中查看当前文件的所有消息,顺便说一下,这会告诉您 PSSA 发现您的代码片段存在其他潜在问题。
  • 要配置应用哪些规则(警告哪些潜在问题),请使用 >PowerShell: Select PSScriptAnalyzer Rules从命令面板。
  • 规则名称,如 PSAvoidGlobalVars , 大多是不言自明的; rules documentation描述它们(没有 PS 前缀);还有一个best practices topic .
  • 重要 :
  • 在选中/取消选中(或按 Enter 键)感兴趣的规则后,请务必在 Confirm 上按 Enter 键。顶部的菜单项,否则您的更改将不会生效。
  • 从 v2019.11.0 开始,这些选择不再保留(仅在当前 session 中被记住)- 参见 this GitHub issue

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

    单机使用:
  • 安装 PSScriptAnalyzer PowerShell 库中的模块;例如。:
  • Install-Module -Scope CurrentUser PSScriptAnalyzer
  • 该模块附带以下 cmdlet:
  • Invoke-ScriptAnalyzer ... lints 脚本文件。
  • Invoke-Formatter ...重新格式化作为字符串传递的代码。
  • Get-ScriptAnalyzerRule ...列出标准和可选的自定义分析器规则。
  • 将脚本的路径传递给 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.

    关于powershell - 如何验证powershell条件语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58529149/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com