无法索引为空数组

Vul*_*ito 1 arrays powershell null

我正在使用一个模板,该模板根据服务器备份成功与否的条件设置单元格颜色。

我有下面的代码不断抛出错误:无法索引为空数组:

无法索引为空数组。
在C:\ Users \ admin \ Desktop \ new.html.ps1:65 char:17
+ ... $ Value = $ Search.Matches [$ Index] .Groups [1] .Value -as [dou ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~
    + CategoryInfo:InvalidOperation:(:) [],RuntimeException
    + FullyQualifiedErrorId:NullArray

最终输出仍会产生正确的结果(颜色等),但是如何设置脚本以忽略任何空值,以使我不再收到这些错误?我已经测试了条件'if($ Value -ne $ null)'的效果,但是在单元格上没有显示颜色。

码:

Process {
    foreach ($Line in $InputObject) {
        if ($Line.IndexOf("<tr><th") -ge 0) {
            Write-Verbose "$(Get-Date): Processing headers..."
            $Search = $Line | Select-String -Pattern '<th ?[a-z\-:;"=]*>(.*?)<\/th>' -AllMatches
            $Index = 0
            foreach ($Match in $Search.Matches) {
                if ($Match.Groups[1].Value -eq $Property) {
                    break
                }
                $Index ++
            }
            if ($Index -eq $Search.Matches.Count) {
                Write-Warning "$(Get-Date): Unable to locate property: $Property in table header"
                exit
            }
            Write-Verbose "$(Get-Date): $Property column found at index: $Index"
        }

        if ($Line -match "<tr( style=""background-color:.+?"")?><td") {
            $Search = $Line | Select-String -Pattern '<td ?[a-z\-:;"=]*>(.*?)<\/td>' -AllMatches
            $Value = $Search.Matches[$Index].Groups[1].Value -as [double]
            if (-not $Value) {
                $Value = $Search.Matches[$Index].Groups[1].Value
            }
            if (Invoke-Command $Filter) {
                if ($Row) {
                    Write-Verbose "$(Get-Date): Criteria met!  Changing row to $Color..."
                    if ($Line -match "<tr style=""background-color:(.+?)"">") {
                        $Line = $Line -replace "<tr style=""background-color:$($Matches[1])","<tr style=""background-color:$Color"
                    } else {
                        $Line = $Line.Replace("<tr>","<tr style=""background-color:$Color"">")
                    }
                } else {
                    Write-Verbose "$(Get-Date): Criteria met!  Changing cell to $Color..."
                    $Line = $Line.Replace($Search.Matches[$Index].Value,"<td style=""background-color:$Color"">$Value</td>")
                }
            }
        }         
        Write-Output $Line
    }
}     
End {
    Write-Verbose "$(Get-Date): Function Set-CellColor completed"
}
Run Code Online (Sandbox Code Playgroud)

小智 5

这里的问题是,您试图在一个循环中索引到一个长度为零(根本没有任何内容)的数组。我认为这是因为正在处理的行之一根本没有匹配项。

您可以使用某种方法在尝试访问索引之前检查是否完全匹配。

就像是..

if ($Search.Matches.Count -gt 0) {

}
Run Code Online (Sandbox Code Playgroud)

如果您想抑制错误,则可以使用类似

-errorAction SilentlyContinue

抑制错误。