如何自动检查powershell脚本文件?

Tim*_*ith 5 validation powershell

我想为一些生成powershell脚本的代码编写单元测试,然后检查脚本是否具有有效的语法.

在没有实际执行脚本的情况下执行此操作的好方法是什么?

.NET代码解决方案是理想的,但是我可以通过启动外部进程来使用命令行解决方案.

Wil*_* M. 18

我偶然Get-Command -syntax 'script.ps1'发现它简洁而有用。

  • 这会提供详细的语法错误报告(如果有);否则显示脚本的调用语法(参数列表)。这比接受的答案更容易用于快速错误检查。 (8认同)
  • @royappa:此答案仅因您的评论而有用,该评论的信息量比答案多 10 倍。两者都+1。 (3认同)
  • 对我来说,这只是生成脚本文件的名称。 (2认同)
  • 确实如此。现在在有语法错误的脚本上尝试一下。 (2认同)

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)


Mat*_*ore 5

PS Script Analyzer是开始静态分析代码的好地方。

PSScriptAnalyzer 通过对正在分析的脚本应用一组内置或自定义规则,提供脚本分析并检查脚本中的潜在代码缺陷。

它还与Visual Studio Code集成。

有许多策略可以将 PowerShell 模拟为单元测试的一部分,也可以看看 Pester。

脚本专家使用 Pester 对 PowerShell 代码进行单元测试 PowerShellMagazine
Get Started With Pester(PowerShell 单元测试框架)