views:

249

answers:

1

Background: Here the goal is to do some basic commands in powershell using select-string. For some reason, there are certain things that are not working as expected.

Assume the following:

    $vfilter = 'c:/foo/bar/files/*.htm';
    Select-String -path $vfilter -pattern ".*DOCTY.*"  |
        sort LineNumber |
        where-object { $_.Filename -match "02" } |
        format-list |
        out-file c:/00junk.txt;

... where this is the output ...

    IgnoreCase : True
    LineNumber : 1
    Line       : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "ht
                 tp://www.w3.org/TR/html4/loose.dtd">
    Filename   : 02junk.htm
    Path       : C:\ ... \02junk.htm
    Pattern    : .*DOCTY.*
    Context    :
    Matches    : {<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "h
                 ttp://www.w3.org/TR/html4/loose.dtd">}

Questions:

1) How can i prevent powershell from wrapping the text of "Line" and "Matches" properties. Since this is being sent to a text file, I do not care about console width and therefore I do not want any text wrapping to occur.

2) Suppose I want to do my own custom output with a multi-line string. In Ruby (for example) I could do it like this:

    custom_string = '';
    items.each{|myitem|
        custom_string += %Q[
            ### begin output ###
            HereIs::LineNumber! --> #{myitem['LineNumber']}
            HereIs::Path!       --> #{myitem['Path']}
            This is the actual line (below):

            #{myitem['Line']}
        ]
    }
    custom_string.tofile('c:/00junk.txt');

How can I get powershell to do the same or similar thing?

3) How could I do 2) above with a powershell here-string?

+6  A: 

1) To prevent wrapping you can specify a huge width parameter for Out-File.

2) Use ForEach-Object (alias %) to generate your string:

$vfilter = 'c:/foo/bar/files/*.htm';
Select-String -path $vfilter -pattern ".*DOCTY.*"  |
    sort LineNumber |
    where-object { $_.Filename -match "02" } |
    ForEach-Object {
@"
Line Number: $($_.LineNumber)
Path:        $($_.Path)
This is the actual line (below):

$($_.Line)

"@
    } |
    out-file c:/00junk.txt;
dahlbyk