Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning Output of Select-String in PowerShell

Tags:

powershell

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.

like image 302
Michael Sorens Avatar asked Oct 17 '25 06:10

Michael Sorens


1 Answers

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

like image 126
mjolinor Avatar answered Oct 21 '25 07:10

mjolinor