Select 多行字符串中的多个子字符串

Select multiple substrings from a multiline string

我正在尝试创建一个 PowerShell 脚本来从大型日志文件中选择特定的行。使用 Select-String,我已经将数据缩减到多行字符串中我需要的行。现在我想进一步将它按摩到 return 只有来自这些行的 ID 号,在一个逗号分隔的字符串中。

当前代码:

if (Select-String $SearchFile -Pattern $SearchString -Quiet) {
    Write-Host "Error message found"
    $body += Select-String $SearchFile -Pattern $SearchString -Context 1,0 |
             foreach {$_.Context.DisplayPreContext} | Out-String
    Send-MailMessage (email_info_here) -Body $body
} else {
    Write-Host "No errors found"
}

目前return正在处理以下字符串:

INFO | Creating Batch for 197988 | 03/24/2016 02:10 AM
INFO | Creating Batch for 202414 | 03/24/2016 02:10 AM
INFO | Creating Batch for 173447 | 03/24/2016 02:10 AM

想要输出格式:

197988, 202414, 173447

如果 Body 包含这些行,那么您只需要拆分并索引到包含我们数据的列。

$body | ForEach-Object {$psitem.Split()[5]}
197988
202414
173447  

在此示例中,我们调用 ForEach-Object 来制作一个小代码块以在每一行上执行。然后,我们调用该行的 $split() 方法来拆分空格。然后我们使用 $psitem[5].

索引到第五列

假设您想再次将这些行保存回 $body,只需将 $body = 添加到第 1 行的前面即可。

编辑:多行字符串与数组

在最初的 post 中,$body 变量是使用 Out-String 作为管道中的最后一个命令创建的。这将使它成为一个多行字符串。省略 | Out-String 部分会使 $body 成为一个字符串数组。后者(一个数组)更容易使用,并且是上面的答案所假设的,因为使用 foreach.

很容易遍历数组中的每一行

两者之间的转换是这样完成的:

$string = @"
INFO | Creating Batch for 197988 | 03/24/2016 02:10 AM
INFO | Creating Batch for 202414 | 03/24/2016 02:10 AM
INFO | Creating Batch for 173447 | 03/24/2016 02:10 AM
"@

$array = @(
"INFO | Creating Batch for 197988 | 03/24/2016 02:10 AM"
"INFO | Creating Batch for 202414 | 03/24/2016 02:10 AM"
"INFO | Creating Batch for 173447 | 03/24/2016 02:10 AM"
)

$array_from_string = $string -split("`n")
$string_from_array = $array | Out-String

为了使答案有效,您需要确保 $body 是一个数组,否则您将只会得到一个 ID 号:

$string | Foreach-Object {$psitem.Split()[5]}
197988

这可能是一种肮脏的方式,但它有效:

#This can also be your variable
$log = gc "C:\[log path here]"

#Remove beginning of string up to ID
$log = $log -replace '(.*?)for ' , ""

#Select first 6 characters since all IDs shown are 6 characters
$logIDs = @()
foreach($line in $log){
    $logIDs += $line.substring(0,6)
}

### At this point $logIDs contains all IDs, now we just need to comma separate them ###

$count = 1
foreach($ID in $logIDs){
    if($count -eq $logIDs.count){
        $result += $ID
    }
    else{
        $result += $ID+", "
        $count++
    }
}

#Here are your results separated by commas
$result

希望这对您有所帮助,如果您需要任何类型的变体,请告诉我。

Out-String替换为匹配每个结果行的数字部分的Where-Object过滤器,提取数字子匹配,并加入结果:

$body += (Select-String $SearchFile -Pattern $SearchString -Context 1,0 |
         ForEach-Object { $_.Context.DisplayPreContext } |
         Where-Object { $_ -match 'for (\d+) \|' } |
         ForEach-Object { $matches[1] }) -join ', '