检查uri内容与powershell和警报字符串匹配

时间:2017-02-17 10:03:45

标签: regex powershell powershell-v3.0

我正在执行此代码:

$web = Invoke-WebRequest http://x.x.x.x:60210/CoreApi/api/Healthcheck
$web.tostring()

$web中的回复如下。

  

HealthStatus:DBConnectionSuccess:True EventStoreConnectionSuccess:True UnpublishedEvents:0 AzureBusConnectionSuccess:True Errors:NONE

我需要为条件UnpublishedEvents创建警报:[> 10]。有人可以用字符串匹配逻辑来帮助我。

2 个答案:

答案 0 :(得分:2)

您可以使用带有命名捕获组的正则表达式来执行此操作,如下所示:

$input = "HealthStatus:DBConnectionSuccess:True EventStoreConnectionSuccess:True UnpublishedEvents:20 AzureBusConnectionSuccess:True Errors:NONE"
$isMatch = $input -match "UnpublishedEvents:(?<UnpubEventCount>\d+)"
if ($isMatch)
{
    return $Matches.UnpubEventCount -gt 10
}
else
{
    Write-Error "UnpublishedEvents not found"
}

$Matches是使用-match运算符时设置的“魔术”变量。

答案 1 :(得分:1)

以下是使用正则表达式的基本解决方案:

$output = 'HealthStatus:DBConnectionSuccess:True EventStoreConnectionSuccess:True UnpublishedEvents:11 AzureBusConnectionSuccess:True Errors:NONE'

$unpublishedEvents = 0

$regex = 'UnpublishedEvents:([0-9]+)'

$match = [regex]::match($output, $regex)
if ($match.Success)
{
  $unpublishedEvents = $match.Groups[1].Value
}

if ($unpublishedEvents -gt 10)
{
  Write-Host "Some alert! ($unpublishedEvents events)"
}