Tim*_*ith 5 validation powershell
我想为一些生成powershell脚本的代码编写单元测试,然后检查脚本是否具有有效的语法.
在没有实际执行脚本的情况下执行此操作的好方法是什么?
.NET代码解决方案是理想的,但是我可以通过启动外部进程来使用命令行解决方案.
Wil*_* M. 18
我偶然Get-Command -syntax 'script.ps1'发现它简洁而有用。
Mat*_*sen 10
您可以通过运行代码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'
}
Run Code Online (Sandbox Code Playgroud)
这很容易变成一个简单的功能:
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)
}
Run Code Online (Sandbox Code Playgroud)
然后使用像:
if(Test-Syntax C:\path\to\script.ps1){
Write-Host 'Script looks good!'
}
Run Code Online (Sandbox Code Playgroud)
PS Script Analyzer是开始静态分析代码的好地方。
PSScriptAnalyzer 通过对正在分析的脚本应用一组内置或自定义规则,提供脚本分析并检查脚本中的潜在代码缺陷。
它还与Visual Studio Code集成。
有许多策略可以将 PowerShell 模拟为单元测试的一部分,也可以看看 Pester。
脚本专家使用 Pester 对 PowerShell 代码进行单元测试 PowerShellMagazine
的Get Started With Pester(PowerShell 单元测试框架)