如何在文本文件中搜索字符串并使用结果和 CSV 文件的内容执行查找?

How to search a text file for string and perform a lookup using results and the contents of a CSV file?

我一直在使用读取文件并提取错误代码的 PowerShell 脚本。它快速、简单并且可以完成我想要的工作,但我现在被要求与广大观众分享它,所以我需要让它更强大一些。

我遇到的问题是我需要从我的脚本中获取输出并使用它来查找 CSV 文件,以便我在末尾得到一个用户友好的 table 列表:

  1. 每个错误发生的次数(降序)
  2. 错误代码
  3. 它向最终用户显示的相应错误消息

这是源文件中的行格式,一般在2000行以上

17-12-2016,10:17:44:487{String=ERROR->(12345678)<inData:{device=printer, formName=blah.frm, eject=FALSE, operation=readForm}><outData:{fields=0, CODE=, field1=}> <outError:{CODE=Error103102, extendedErrorCode=-1, VARS=0}>}

这是我当前的脚本:

$WS = Read-Host "Enter computer name"
$date = Read-host "Enter Date"

# Search pattern for select-string (date always at the beginning of the line and the error code somewhere further in)
$Pattern = $date+".*<outError:{CODE="

# This find the lines in the files that contain the search pattern
$lines = select-string -path "\$WS\c$\folder\folder\file.dat" -pattern $Pattern

# This is the specific Error code pattern that I'm looking for in each line
$regex = [regex] 'Error\d{1,6}'
$Var = @()

# Loops through each line and extracts Error code
foreach ($line in $lines) { $a = $line -match $regex 
# Adds each match to variable
$Var += $matches.Values

 }

# Groups and sorts results in to easy to read format 
$Var | group | Sort-Object -Property count -descending

这是它给我的结果:

Count Name                      Group
----- ----                      -----
   24 Error106013                {Error106013, Error106013, Error106013, Error106013...}
   14 Error106109                {Error106109, Error106109, Error106109, Error106109...}
   12 Error203002                {Error203002, Error203002, Error203002, Error203002...}

我需要查找的 CSV 非常简单,每行只有 2 个值,格式如下:

Code,Error message

我需要做的是这样的:

Count Name                      Error Message
----- ----                      -----
   24 Error106013                Error:blah
   14 Error106109                Error:blah,blah
   12 Error203002                Error:blah,blah,balh

Google 让我失望了,所以我希望有人至少可以为我指明正确的方向。

未测试,但它应该适用于简单的 计算 属性 - 只需将最后一行替换为:

$errorMap = Import-Csv 'your_errorcode.csv'
$Var | Group-Object | Sort-Object -Property count -descending | 
    Select-Object Count, Name, @{l='Error Message'; e={($errorMap | Where-Object Code -eq $_.Name)."Error message"}}

注意:您还必须替换 CSV 的路径。