I have been digging through log files to try to find information about errors that I’m troubleshooting. I start out with some information that I’m searching the log files for. For example:


    # find the troublesome user
    $occurrences = ls -r -i *.log | select-string 'Dan'

Great. Now I have an array of Microsoft.PowerShell.Commands.MatchInfo objects in my $occurrences variable. The MatchInfo has the following members (some members removed for clarity):


    TypeName: Microsoft.PowerShell.Commands.MatchInfo

    RelativePath   Method     System.String RelativePath(String directory)
    Filename       Property   System.String Filename {get;}
    IgnoreCase     Property   System.Boolean IgnoreCase {get;set;}
    Line           Property   System.String Line {get;set;}
    LineNumber     Property   System.Int32 LineNumber {get;set;}
    Path           Property   System.String Path {get;set;}
    Pattern        Property   System.String Pattern {get;set;}

Now I want to run through all the matches and take a peek at the 20 text lines above and below the match like this:

    # show the context around each match and pause 
    $occurrences | %{ (get-content $_.Path)[$($_.LineNumber - 20)..$($_.LineNumber + 20)]; pause; }

Pause is not a built-in command. I’m using the pause function described here Pause on PowerShell Team Blog

Sorry, comments are closed for this article.