2016-07-15 79 views
0

我有一個錯誤日誌文件,想要複製所有不匹配設置錯誤字符串的行。所以基本上我正在建立一個無法識別錯誤的單獨文件。刪除基於字符串的行

我定義所有知道的錯誤類型

# Define all the error types that we need to search on 
$error_1 = "Start Date must be between 1995 and 9999" 
$error_2 = "SYSTEM.CONTACT_TYPE" 
$error_3 = "DuplicateExternalSystemIdException" 
$error_4 = "From date after To date in address" 
$error_5 = "Missing coded entry for provider type category record" 

,這是我做的讀取文件

(Get-Content $path\temp_report.log) | 
    Where-Object { $_ -notmatch $error_1 } | 
    Out-File $path\uncategorised_errors.log 
(Get-Content $path\temp_report.log) | 
    Where-Object { $_ -notmatch $error_2 } | 
    Out-File $path\uncategorised_errors.log 
(Get-Content $path\temp_report.log) | 
    Where-Object { $_ -notmatch $error_3 } | 
    Out-File $path\uncategorised_errors.log 

我輸入文件什麼是這樣的:

15 Jul 2016 20:02:11,340 ExternalSystemId cannot be the same as an existing provider 
15 Jul 2016 20:02:11,340 XXXXXXXXXXXXXXXXXXXXXXXXX 
15 Jul 2016 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ 
15 Jul 2016 20:02:11,340 DuplicateExternalSystemIdException 
15 Jul 2016 20:02:11,340 DuplicateExternalSystemIdException 
15 Jul 2016 20:02:11,340 SYSTEM.CONTACT_TYPE

和我出門的時候完全一樣,我應該只有3條線:

15 Jul 2016 20:02:11,340 ExternalSystemId cannot be the same as an existing provider 
15 Jul 2016 20:02:11,340 XXXXXXXXXXXXXXXXXXXXXXXXX 
15 Jul 2016 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ

回答

1

嘗試:

(Get-Content $path\temp_report.log) | Where-Object { $_ -notmatch $error_1 -and $_ -notmatch $error_2 -and $_ -notmatch $error_3 -and $_ -notmatch $error_4 -and $_ -notmatch $error_5} | Out-File $path\uncategorised_errors.log 
+0

作品。我剛剛獲得這項工作,但你的答案更優雅,只是一個班輪。 $ result = Get-Content $ path \ temp_report.log $ result | Where-Object {$ _ -notmatch [regex] :: escape($ error_1)} | Set-Content $ path \ uncategorised_errors.log – zoomzoomvince

1

充分利用已知錯誤的陣列,完全使用Select-String

[email protected](
    "Start Date must be between 1995 and 9999", 
    "SYSTEM.CONTACT_TYPE", 
    "DuplicateExternalSystemIdException", 
    "From date after To date in address", 
    "Missing coded entry for provider type category record" 
) 

Select-String -Path D:\log.txt -NotMatch -Pattern $errors 
+0

我會添加'-SimpleMatch'來避免過濾器字符串中特殊字符的意外結果。 –