[英]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 Code的PowerShell 扩展中。
它会捕捉到您的问题,并发出以下消息:
您的意思是使用重定向运算符“>”吗?
PowerShell 中的比较运算符是“-gt”(大于)或“-ge”(大于或等于)。
安装后,打开脚本进行编辑,您会看到> 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
模块; 例如:
Install-Module -Scope CurrentUser PSScriptAnalyzer
该模块附带以下 cmdlet:
Invoke-ScriptAnalyzer
... lints 脚本文件。Invoke-Formatter
... 重新格式化作为字符串传递的代码。Get-ScriptAnalyzerRule
... 列出标准和可选的自定义分析器规则。 将脚本的路径传递给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.