2013-05-03 93 views
1

我有一個問題,得到一個正則表達式來提取字符串的一部分,我看不出我做錯了什麼。Powershell正則表達式不觸發

字符串:

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] 
} 

我想提取文本網絡位置

任何指針將不勝感激!

按照要求的代碼 $事件更充分的範圍=獲取,事件日誌應用-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 
} 
+0

我用你的例子測試,併爲我工作。添加你的錯誤... – 2013-05-03 10:21:55

+0

這不是錯誤,但目的地結束了一個空的變量。 – Trinitrotoluene 2013-05-03 10:22:46

+0

檢查'$ message'的內容,如果是[string]類型。如果你使用你的例子來模擬,你會發現這個正則表達式是好的,我會在'(。*)'之後添加一個額外的空格來將它從捕獲中排除。 – 2013-05-03 10:26:35

回答

0

好吧,我張貼作爲回答這個時候,更靈活的格式,並因爲我相信這將最終解決問題。 )

嘗試這種情況:

$destinationregex = '(?s)Destination: ([^\r\n]*).*?Start time:' 

(?s)意味着通配符可以匹配換行符。分組([^\r\n]*)匹配到該行的結尾,並且.*?匹配換行符。下面將工作太:

$destinationregex = 'Destination: (.*?)\r\nStart time:'

事實上,因爲你真的只是想從後匹配「目標:」到該行的末尾,你可能只是這樣做,這是最簡單的(除非你特別想確保你只能匹配,如果「開始時間:」是第二天的事情):

$destinationregex = 'Destination: (.*)'

如果仍然不行,則可能是因爲$消息被解讀爲一個數組而不是一個字符串。您可以通過在設置$ message後立即添加調試行$message.GetType()來輕鬆進行測試。如果它是一個數組,可以嘗試設置$消息這樣(除了使用正則表達式的一個以上):

$message = $event.message | 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 
}