When I use select-string
I almost always want my output aligned, i.e. the file names, the line numbers, and the found text should all be aligned into columns. Visually it is much less distracting and usually allows spotting discrepancies much more easily. As a trivial example I have injected an extra space in the middle file here:
PS> Get-ChildItem *.cs | Select-StringAligned -pattern override
---
FileWithQuiteALengthyName.cs : 34: protected override void Foo()
ShortName.cs : 46: protected override void Bar()
MediumNameFileHere.cs :123: protected override void Baz()
---
Unfortunately, Select-String
does not do that; in reality it gives this--can you spot the extra space here?
PS> Get-ChildItem *.cs | Select-String -pattern override
---
FileWithQuiteALengthyName.cs:34: protected override void Foo()
ShortName.cs:46: protected override void Bar()
MediumNameFileHere.cs:123: protected override void Baz()
---
Is there a way to force Select-String
to align its output columns?
EDIT:
Oops! I forgot one important part: I would like to also include the -Context
parameter if possible so one could get an arbitrary number of lines before and after the match.
Using objects:
Get-ChildItem *.cs | select-string -pattern override |
select Filename,LineNumber,Line | Format-Table -AutoSize
and it's also fit to export to csv if you decide you want to keep it.
Adding that requirement to be able to also use context complicates things considerably.
function ssalign {
begin {$display = @()}
process {
$_ -split "`n" |
foreach {
$display +=
$_ | New-PSObjectFromMatches -Pattern '^(.+)?:([\d]+):(.+)' -Property $null,File,Line,Text
}
}
end {
$display |
foreach {$_.line = ':{0,5}:' -f $_.line}
$display | ft -AutoSize -HideTableHeaders
}
}
Get-ChildItem *.cs | Select-StringAligned -pattern override | ssalign
Get that New-PSObjectFromMatches function here: http://gallery.technet.microsoft.com/scriptcenter/New-PSObjectFromMatches-87d8ce87
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With