我想为一些生成Powershell脚本的代码编写一个单元测试,然后检查该脚本是否具有有效的语法。
在不实际执行脚本的情况下执行此操作的好方法是什么?
.NET 代码解决方案是理想的,但我可以通过启动外部进程使用的命令行解决方案就足够了。
我偶然发现了Get-Command -syntax 'script.ps1'
,发现它简洁而有用。
ETA 来自下面的评论: 这给出了详细的语法错误报告(如果有的话(;否则,它会显示脚本的调用语法(参数列表(。
您可以通过Parser
运行代码并观察它是否引发任何错误:
# Empty collection for errors
$Errors = @()
# Define input script
$inputScript = 'Do-Something -Param 1,2,3,'
[void][System.Management.Automation.Language.Parser]::ParseInput($inputScript,[ref]$null,[ref]$Errors)
if($Errors.Count -gt 0){
Write-Warning 'Errors found'
}
这可以很容易地变成一个简单的函数:
function Test-Syntax
{
[CmdletBinding(DefaultParameterSetName='File')]
param(
[Parameter(Mandatory=$true, ParameterSetName='File', Position = 0)]
[string]$Path,
[Parameter(Mandatory=$true, ParameterSetName='String', Position = 0)]
[string]$Code
)
$Errors = @()
if($PSCmdlet.ParameterSetName -eq 'String'){
[void][System.Management.Automation.Language.Parser]::ParseInput($Code,[ref]$null,[ref]$Errors)
} else {
[void][System.Management.Automation.Language.Parser]::ParseFile($Path,[ref]$null,[ref]$Errors)
}
return [bool]($Errors.Count -lt 1)
}
然后像这样使用:
if(Test-Syntax C:pathtoscript.ps1){
Write-Host 'Script looks good!'
}
PS 脚本分析器是开始静态分析代码的好地方。
PSScriptAnalyzer 提供脚本分析和潜在检查 通过应用一组内置或 对正在分析的脚本进行自定义规则。
它还与Visual Studio Code集成。
作为单元测试的一部分,有许多策略可以模拟PowerShell,也可以看看Pester。
脚本专家的单元测试PowerShell代码与纠缠
PowerShellMagazine's Get Started with Pester(PowerShell单元测试框架(