.net Powershell正则表达式未触发

.net Powershell正则表达式未触发,.net,regex,powershell,powershell-2.0,.net,Regex,Powershell,Powershell 2.0,我在让正则表达式提取字符串的一部分时遇到问题,我看不出我做错了什么 字符串: Backup job DailyBackupToNAS completed successfully. Destination: Network location Start time: 01/05/2013 05:00:28 End time: 01/05/2013 05:39:13 Duration: 00:38:45.5875346 守则: $destinationregex = "Destination:

我在让正则表达式提取字符串的一部分时遇到问题,我看不出我做错了什么

字符串:

Backup job DailyBackupToNAS completed successfully.   Destination: Network location Start time: 01/05/2013 05:00:28 End time: 01/05/2013 05:39:13 Duration: 00:38:45.5875346
守则:

$destinationregex = "Destination: (.*)Start time:"
If ($message -match $destinationregex)
{
    $destination = $matches[1]
}
我正在尝试提取文本网络位置

任何提示都将不胜感激

应要求,提供更完整的代码范围 $events=获取事件日志应用程序-源备份辅助-最新50

Foreach ($event in $events)
{
  $message = $event.message
  $destinationregex = "Destination: (.*)Start time:"
  If ($message -match $destinationregex)
  {
    $destination = $matches[1]
  }
  Else
  {
    $destination = "Unknown"
  }
  Write.Host $destination
}

好的,我这次发帖是为了更灵活的格式,因为我相信这将最终解决这个问题

试试这个:

$destinationregex = '(?s)Destination: ([^\r\n]*).*?Start time:'
s表示通配符可以匹配换行符。分组[^\r\n]*匹配到行尾,而。*?匹配换行符。以下措施也会奏效:

$destinationregex='目的地:.*.\r\n开始时间:'

事实上,因为您确实只想从Destination:之后匹配到行的末尾,所以您可以这样做,这是最简单的,除非您特别想确保仅在Start time:是下一件事时匹配:

$destinationregex='Destination:.'

如果仍然不起作用,可能是因为$message被读取为数组而不是字符串。通过在设置$message后立即添加调试行$message.GetType,可以轻松地测试这一点。如果是数组,除了使用上面的正则表达式之外,还可以尝试通过这种方式设置$message:

foreach ($event in $events)
{
  $message = $event.message | Out-String
  $destinationregex = 'Destination: (.*)'
  If ($message -match $destinationregex)
  {
    $destination = $matches[1]
  }
  else
  {
    $destination = "Unknown"
  }
  Write-Host $destination
}
$message=$event.message |输出字符串

事实上,这样做在任何情况下都有效,但如果| Out字符串已经是字符串,则它是多余的,尽管它不会造成伤害

为了清楚起见,这里是修改后的代码块,我认为它最终会结束,这取决于对上述问题的回答:

foreach ($event in $events)
{
  $message = $event.message | Out-String
  $destinationregex = 'Destination: (.*)'
  If ($message -match $destinationregex)
  {
    $destination = $matches[1]
  }
  else
  {
    $destination = "Unknown"
  }
  Write-Host $destination
}

我已经用你的例子进行了测试,对我很有用。添加您的错误…它不是错误,但目的地是一个空变量。检查$message的内容,如果是[string]类型。如果您使用您的示例进行模拟,您将看到正则表达式很好,我会在.*之后添加一个额外的空格,以将其从捕获中排除。变量类型很好,因为下面有一个正则表达式在同一个变量$message上运行,并且执行正确。添加了空格,没有区别。嗯,但是如果我把字符串作为变量直接放进去,它就可以工作了。