计算错误日志中的错误数并比较 |电源外壳 (V2) |数组数据结构

Count # of errors in error log & Compare | Powershell (V2) | Array Data Structures

我有一个错误代码的散列table,以及它们在错误日志目录中出现的最大次数table。 像这样:

Key    Value
err1   2
err2   1

此 table 是根据控制文件 (xml) 的输入动态创建的,因此元素的数量可以更改。

我希望现在能够查找 'err1' 和 'err2',计算它们出现的次数,然后将其与散列 table 进行比较。

所以我有这样的东西:

ForEach($file in $logs){
    ForEach($key in $hashTable.keys){
        If(Select-String $file -pattern $key){
            #get key value, increment a counter for this key value (error code)
        }
    }
}

#Psuedo for next step...
<#
 ForEach($key in $hashTable.keys){
      If (CountFound > Key.Value) {
     write-host $("Error: " + $key + " occurred too much."
    }
 }
#>

PowerShell 中是否有擅长存储 variable/value 对且易于快速修改的数据结构?

我不想为每个键值创建一个数组,然后每次在文件中找到匹配的错误代码时向该数组添加一个元素,然后计算不同数组的长度。但这是我能想到的最好的解决方案。

我认为这可能是实现我的目标的最简单方法。

ForEach($key in $hashTable.keys){
$count = 0
    ForEach($file in $logs){
        If(Select-String $file -pattern $key){
            $count++
        }
    }
    If($count -gt $hashTable.Get_Item($key){
        #Do something
    }
}

这样我就完全避免了另一种数据结构。

您可以采用面向对象的方式,让 class 表示您从外部源读取的每种错误类型,然后根据您的逻辑更新这些错误实例。由于您只要求更好的结构来保存您的数据,因此我只关注这一点。你已有的逻辑。

$errorClass = @"
public class Error
{
    public Error(string errorCode, int maxOccurances) {
        ErrorCode = errorCode;
        MaxOccurances = maxOccurances;
    }

    public string ErrorCode;
    public int MaxOccurances;
    public int ActualOccurances;
}
"@

Add-Type -TypeDefinition $errorClass

$error1 = New-Object Error("Err1", 2) # You get these values from xml
$error1.ActualOccurances = 5 # Update this property based on your logic

$error2 = New-Object Error("Err2", 1)
$error2.ActualOccurances = 3

$errArray = @($error1, $error2)

foreach ($err in $errArray) {
    if ($err.ActualOccurances -gt $err.MaxOccurances) {
        write-host $("Error: '" + $err.ErrorCode + "' occurred too much.")
    }
}

输出:

Error: 'Err1' occurred too much.
Error: 'Err2' occurred too much.