簡體   English   中英

如何驗證 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) 是PowerShell的 linter ,它集成到Visual Studio CodePowerShell 擴展中。

它會捕捉到您的問題,並發出以下消息:

您的意思是使用重定向運算符“>”嗎?
PowerShell 中的比較運算符是“-gt”(大於)或“-ge”(大於或等於)。


在 Visual Studio 代碼中使用:

  • 安裝PowerShell 擴展

  • 安裝后,打開腳本進行編輯,您會看到> 0部分帶有下划線,並且將鼠標懸停在它上面會顯示消息作為工具提示。

  • 您可以在 Problems 視圖中查看當前文件的所有消息( Ctrl-Shift-M或通過菜單, View > Problems ),順便說一下,這會告訴您 PSSA 發現了您的代碼片段的其他潛在問題。

  • 要配置要應用的規則(要警告哪些潛在問題),請使用命令面板中的>PowerShell: Select PSScriptAnalyzer Rules

    • 規則名稱,例如PSAvoidGlobalVars ,大多是不言自明的; 規則文檔描述了它們(沒有PS前綴); 還有一個最佳實踐主題

    • 重要

      • 在選中/取消選中(或按Enter )感興趣的規則后,請務必在頂部的Confirm菜單項上按Enter ,否則您的更改將不會生效。

      • 從 v2019.11.0 開始,這些選擇不再保留(僅在當前的 session 中記住) - 請參閱此 GitHub 問題

請注意,PSSA還提供 PowerShell 代碼的自動(重新)格式化Alt-Shift-F或通過命令調色板>Format Document )。


單機使用:

  • 從 PowerShell 庫安裝PSScriptAnalyzer模塊; 例如:

  • 將腳本的路徑傳遞給Invoke-ScriptAnalyzer cmdlet 以執行 linting。

使用您的代碼,您會看到以下 output (已獲得名為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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM