Powershell 二维数组未按预期工作

Powershell two dimensional array not working as expected

目前我正在从 XML 文件中加载一些数据来为我的脚本配置一些参数 运行,但是 $keywords$maxCounts 是将它们发送到 CheckForKeywords 函数时没有得到正确的值

function Main()
{

#### VARIABLES RELATING TO THE LOG FILE

#contains the log path and log file mask
$logPaths = @()
$logFileMasks = @()

# key value pair for the strings to match and the max count of matches before they are considered an issue
$keywords = @(,@())
$maxCounts = @(,@())


#### FUNCTION CALLS

LoadLogTailerConfig $logConfigPath ([ref]$logPaths) ([ref]$logFileMasks) ([ref]$keywords) ([ref]$maxCounts)

for ($i = 0; $i -lt $logPaths.Count; $i++)
{
    $tail = GetLogTail $numLinesToTail $logPaths[$i] $logFileMasks[$i]

    $tailIssueTable = CheckForKeywords $tail $keywords[$i] $maxCounts[$i]


}

}

# Loads in configuration data for the utility to use
function LoadLogTailerConfig($logConfigPath, [ref]$logPaths, [ref]$logFileMasks, [ref]$keywords, [ref]$maxCounts)
{
    Write-Debug "Loading config file data from $logConfigPath"

    [xml]$configData = Get-Content "C:\Testing\Configuration\config.xml"

    foreach ($log in $configData.Logs.Log) {

        $logPaths.Value += $log.FilePath
        $logFileMasks.Value += $log.FileMask

        $kwp = @()
        $kwc = @()

        foreach ($keywordSet in $log.Keywords.Keyword)
        {
            $kwp += $keywordSet.Pattern
            $kwc += $keywordSet.MaxMatches 
        }

        $keywords.Value += $kwp
        $maxCounts.Value += $kwc
    }
}

# Returns body text for email containing details on keywords in the log file and their frequency
function CheckForKeywords($tail, $keywords, $maxCounts)
{   
    $issuesFound = 0


    for ($i = 0; $i -lt $keywords.Count; $i++)
    {
        $keywordCount = ($tail | Select-String $keywords[$i] -AllMatches).Matches.Count

        Write-Debug $keywords.Count

        Write-Debug (("Match count for {0} : {1}" -f $keywords[$i], $keywordCount))

        if ($keywordCount -gt $maxCounts)
        {
            #do stuff
        }
    }

    return ""
}

Main

您正在做的不是二维数组,而是嵌套数组。通过写作

$keywords = @(,@())
$maxCounts = @(,@())

您正在创建一个只有一个元素的数组。此元素是一个包含零个元素的数组。你不需要那个。所以把上面的改成:

$keywords = @()
$maxCounts = @()

现在当你这样做时:

$keywords.Value += $kwp
$maxCounts.Value += $kwc

powershell 解开右侧的数组并逐个元素与左侧的数组连接。那不是你想要的。所以将其更改为

$keywords.Value += @(,$kwp)
$maxCounts.Value += @(,$kwc)

附带说明,通过 ref 参数使用在 powershell 中不是惯用的,并且使用该方法获得帮助并不容易。我建议更改您的函数以通过管道传递结果,powershell 方式,将来支持您的脚本的人会很感激。您可以将想要 return 作为对象属性的不同类型的值建模,而不是 return 该对象。祝你好运。