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

时间:2017-04-04 17:13:19

标签: validation powershell

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

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

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

3 个答案:

答案 0 :(得分:9)

您可以通过Parser运行代码并观察它是否会引发任何错误:

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:\path\to\script.ps1){
    Write-Host 'Script looks good!'
}

然后使用:

{
    "_type": "SearchResponse",
    "webPages": {
        "webSearchUrl": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=sFk5GtkV8PxaqVq0K3GniaQOQJqKR2jqw1udftLC9QE&v=1&r=https%3a%2f%2fwww.bing.com%2fsearch%3fq%3dcontemporary%2bfurniture&p=DevEx,5336.1",
        "totalEstimatedMatches": 46000000,
        "value": [{
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.0",
            "name": "Contemporary Furniture. Modern and Scandinavian designs.",
            "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=Q0wwocl-JR44YrK1RsR_5rSqO4KPlSPx0KgUi-sMocA&v=1&r=https%3a%2f%2fcontemporaryfurniture.com%2f&p=DevEx,5080.1",
            "displayUrl": "https:\/\/contemporaryfurniture.com",
            "snippet": "The finest in contemporary and modern furniture. Imported and domestic styles, bedrooms, sofas, home office, more. Shop online or visit our NY showroom.",
            "deepLinks": [{
                "name": "Bedrooms",
                "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=jo1rIVengiXnaKOkFczZ54qrp9-L4W2jb1sJ41jl04g&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbedrooms-19%2f&p=DevEx,5072.1",
                "snippet": "Bedroom sets including beds, dressers, nightstands and chests. Produced in various woods and lacquers. Contemporary, scandinavian and modern designs."
            }, {
                "name": "Dining Rooms",
                "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=EsyLPbUccu5BzwCeceP_S5u46vo4gSDMG7vP29BfjFE&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fdining-rooms-12%2f&p=DevEx,5073.1",
                "snippet": "Dining Room sets, dining tables, servers, buffet and china cabinets. Contemporary and Scandinavian styles."
            }, {
                "name": "Barstool",
                "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=6rOwsJH4uT4LzjG833eSRYQgDMCKiogHGdgnokFVSEg&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fbarstool-16%2f&p=DevEx,5074.1",
                "snippet": "Barstools and counterstools contemporary, modern and scandinavian designs produced in wood and metal."
            }, {
                "name": "Chairs",
                "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=ADlw0i43aQhdLC0tHBfjMFjYwiWYHZ3ggdG6RhZv9ss&v=1&r=https%3a%2f%2fwww.contemporaryfurniture.com%2fshop%2fchairs-13%2f&p=DevEx,5075.1",
                "snippet": "Chairs to compliment your living room produced in fabric upholstery and leather. Contemporary and modern designs."
            }],
            "dateLastCrawled": "2017-03-31T17:25:00"
        }, {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.1",
            "name": "Contemporary Furniture | Houzz",
            "url": "http:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=vsM0va_8kehN5ZnPil2frs3eKL16FOHnut88FvEHRsM&v=1&r=http%3a%2f%2fwww.houzz.com%2fphotos%2fcontemporary%2ffurniture&p=DevEx,5098.1",
            "displayUrl": "www.houzz.com\/photos\/contemporary\/furniture",
            "snippet": "Browse a wide selection of contemporary furniture for sale on Houzz, including wood furniture and leather furniture for your dining room, office, bedroom and living room.",
            "dateLastCrawled": "2017-03-30T22:51:00"
        }, {
            "id": "https:\/\/api.cognitive.microsoft.com\/api\/v5\/#WebPages.2",
            "name": "Affordable Modern Furniture, Decor & Lighting online. Free ...",
            "url": "https:\/\/www.bing.com\/cr?IG=B470EF0A41D94B338002992668141CC5&CID=1B1D0110A94966F5383E0B4AA8A067DE&rd=1&h=OwOQI48E8ZhxF8xWw-iB2POJliBV0LIE3CucLePUzeg&v=1&r=https%3a%2f%2fwww.contemporaryfurniturewarehouse.com%2f&p=DevEx,5112.1",
            "displayUrl": "https:\/\/www.contemporaryfurniturewarehouse.com",
            "snippet": "Modern & Contemporary Furniture on sale. Shop for sofas, sectionals, accent chairs, dining chairs, bar stools, office chairs, stools, outdoor furniture & more.",
            "dateLastCrawled": "2017-03-31T02:54:00"
        }

答案 1 :(得分:4)

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

  

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

它还与Visual Studio Code集成。

有许多策略可以将PowerShell作为单元测试的一部分进行模拟,并且还可以查看Pester。

脚本专家Unit Testing PowerShell Code With Pester
PowerShellMagazine' Get Started With Pester (PowerShell unit testing framework)

答案 2 :(得分:0)

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