2017-04-04 23 views
2

我想爲一些生成powershell腳本的代碼編寫一個單元測試,然後檢查腳本是否有有效的語法。如何自動語法檢查PowerShell腳本文件?

在沒有真正執行腳本的情況下做這件事的好方法是什麼?

.NET代碼解決方案非常理想,但通過啓動外部進程可以使用的命令行解決方案就足夠了。

回答

5

你可以通過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')] 
     [string]$Path, 

     [Parameter(Mandatory=$true, ParameterSetName='String')] 
     [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:\path\to\script.ps1){ 
    Write-Host 'Script looks good!' 
} 
+0

這可能是最直接的點答案這個問題。礦是更普遍的單元測試。 –

3

PS Script Analyzer是開始靜態分析代碼的好地方。

PSScriptAnalyzer通過施加一組內置的或在腳本 定製規則的被分析提供了用於在腳本潛在 代碼缺陷腳本分析和檢查。

它也與Visual Studio Code整合。

作爲單元測試的一部分,模擬PowerShell有許多策略,並且還可以看一下Pester。

腳本專家的Unit Testing PowerShell Code With Pester
PowerShellMagazine的Get Started With Pester (PowerShell unit testing framework)

+1

古怪我創建的文檔主題這個今天:http://stackoverflow.com/documentation/powershell/9619/psscriptanalyzer-powershell-script-analyzer –

相關問題