This PowerShell one-liner is a convenient way to monitor log files in real-time and quickly spot error messages. The script continuously reads the log and highlights lines that contain the word “error” with a red background, making them easy to identify. It’s a handy tool for troubleshooting or monitoring system activities, especially when dealing with logs generated by tools like DISM.
gc .\dism.log -wait |foreach-object { if ($_ -match "error"){write-host -foregroundcolor white -BackgroundColor red $_} else {write-host $_}}
Explanation:
gc .\dism.log -wait
gc
is short forGet-Content
, a PowerShell cmdlet that reads the content of a file..\dism.log
specifies the file to read, which isdism.log
. This log file is typically generated by the Deployment Imaging Service and Management Tool (DISM), often used for Windows image management.- The
-wait
parameter makesGet-Content
continuously monitor the log file in real-time, displaying new content as it is written to the file. This is especially useful for live monitoring of logs.
| foreach-object
- The
|
symbol (pipeline) sends the output of theGet-Content
cmdlet to the next part of the command. foreach-object
is a loop that processes each line of the log file one by one as it is being read.
- The
if ($_ -match "error")
$_
represents the current line of the log file being processed in the loop.-match "error"
checks if the current line contains the word “error” (case-insensitive by default in PowerShell). This is the key part that identifies lines with errors in the log.
write-host -foregroundcolor white -BackgroundColor red $_
- If the line contains the word “error,” this part of the command prints it to the console with a white foreground (text color) and a red background for visibility, signaling an error.
$_
again represents the line being processed.
else { write-host $_ }
- If the line doesn’t contain “error,” it simply prints the line normally, without any special formatting.
Example:
Suppose you are monitoring the dism.log
file and a line like this is written to the log:
2024-10-11 14:55:12, Error DISM DISM.EXE: Failed to load the provider
In the console, this line will be printed in white text with a red background, making it easy to spot among other log entries.