[英]Powershell Regex not triggering
我在讓正則表達式提取字符串的一部分時遇到問題,但看不到我做錯了什么。
字符串:
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 = get-eventlog應用程序-source BackupAssist -newest 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 = 'Destination: (.*?)\\r\\nStart time:'
實際上,由於您實際上只想從“ Destination:”之后到行尾進行匹配,因此您可以這樣做,這是最簡單的(除非您特別想確保僅在“ Start time: ”是接下來的內容):
$destinationregex = 'Destination: (.*)'
如果仍然不起作用,可能是因為$ message被讀取為數組而不是字符串。 您可以通過在設置$ message之后立即添加調試行$message.GetType()
輕松地進行測試。 如果是數組,請嘗試以這種方式設置$ message(除了使用上述正則表達式之一):
$message = $event.message | Out-String
實際上,無論哪種情況,都可以這樣做,但是| Out-String
如果已經是字符串,則| Out-String
是多余的,盡管它不會造成傷害。
為了清楚起見,這是修改后的代碼塊,我認為它將最終完成,具體取決於上述問題的答案:
foreach ($event in $events)
{
$message = $event.message | Out-String
$destinationregex = 'Destination: (.*)'
If ($message -match $destinationregex)
{
$destination = $matches[1]
}
else
{
$destination = "Unknown"
}
Write-Host $destination
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.