问题
I have an error log file from which want to copy all lines that DON'T match a set error strings. So basically I am building up a separate file of unrecognised errors.
I define all the know error types
# 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"
and this is what I am doing to read in the file
(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
My input file is like this:
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
and my out is exactly the same when I should have only 3 lines:
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:
try it:
(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
回答2:
Make the known errors an array, use Select-String
$errors=@(
"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
来源:https://stackoverflow.com/questions/38405279/remove-lines-based-upon-string