如何用PowerShell提取日志中ERROR后的内容并导出至文件?
Hey there! You already have a great start counting ERROR entries in your ControlOIS.log file—let's build on that to extract the actual error details and save them to a separate file, making it way easier to zero in on issues that need fixing.
Option 1: Export the full ERROR lines
If you want to keep the entire log line (including the timestamp and ERROR label) for context, use this command:
Get-Content "C:\Users\mchalmer\Desktop\ControlOIS.log" | Where-Object { $_.Contains("ERROR") } | Out-File "C:\Users\mchalmer\Desktop\FullErrorEntries.log" -Encoding UTF8
This will take every line that includes "ERROR", and save them all to FullErrorEntries.log in your desktop folder. The -Encoding UTF8 ensures special characters display correctly.
Option 2: Export only the ERROR details (after "ERROR:")
If you just want the specific error message without the timestamp and "ERROR:" label, we can use a regex to extract that portion:
Get-Content "C:\Users\mchalmer\Desktop\ControlOIS.log" | Where-Object { $_.Contains("ERROR") } | ForEach-Object { # Match everything after "ERROR: " and capture it if ($_ -match 'ERROR: (.*)$') { $matches[1] } } | Out-File "C:\Users\mchalmer\Desktop\ErrorDetailsOnly.log" -Encoding UTF8
For your sample log line:
2017-10-01 05:37:51:109 - ERROR: [Service App] Unable to start worker process, Error performing "LogonUser", error code: 87. "The parameter is incorrect"
This command would extract and save:[Service App] Unable to start worker process, Error performing "LogonUser", error code: 87. "The parameter is incorrect"
Both options let you quickly review all error-related content without sifting through the entire log file. Pick whichever fits your troubleshooting workflow best!
内容的提问来源于stack exchange,提问作者Mark Chalmers

