Pants Bike
Pants Bike

Reputation: 13

Format results in table

My script below searches for a specific part number (459279) recursively through a number of txt files.

set-location C:\Users\admin\Desktop\PartNumbers\
$exclude = @('PartNumbers.txt','*.ps1')
$Line = [Environment]::NewLine
Get-ChildItem -Recurse -Exclude $exclude | select-string 459279 | group count | Format-Table -Wrap -AutoSize -Property Count,
@{Expression={$_.Group | foreach { $_.filename} | Foreach {"$_$Line"} }; Name="Filename"},
@{Expression={$_.Group | foreach {$_.LineNumber} | Foreach {"$_$Line"} }; Name="LineNumbers"} | Out-File 459279Results.txt

My Results are:

Count Filename                           LineNumbers
----- --------                           -----------
    2 {Customer1.txt                     {2         
      , Customer2.txt                    , 3        
      }                                  }          

My ideal results would be if this is possible:

Part Number: 459279
Count: 2

Filename                           LineNumbers
--------                           -----------
Customer1.txt                      2         
Customer2.txt                      3        

I have manually retrieved the part number '459279' from "PartNumbers.txt" and searched for it using the script.

I cannot seem to remove/replace the braces and commas to present a clean list.

What I hope to eventually do is to recursively search through "PartNumbers.txt" and produce a report with each part number appended to the next in the style mentioned above.

PartNumbers.txt is formatted:

895725
939058
163485
459279
498573

Customer*.txt are formatted:

163485
459279
498573

Upvotes: 1

Views: 1114

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200503

Something like this should work:

$exclude = 'PartNumbers.txt', '*.ps1'
$root    = 'C:\Users\admin\Desktop\PartNumbers'
$outfile = Join-Path $root 'loopResults.txt'

Get-Content (Join-Path $root 'PartNumbers.txt') | % {
  $partno = $_
  $found = Get-ChildItem $root -Recurse -Exclude $exclude `
             | ? { -not $_.PSIsContainer } `
             | Select-String $partno `
             | % {
               $a = $_ -split ':'
               New-Object -Type PSCustomObject -Property @{
                 'Filename'    = Split-Path -Leaf $a[1];
                 'LineNumbers' = $a[2]
               }
             }

  "Part Number: $partno"
  'Count: ' + @($found).Count
  $found | Format-Table Filename, LineNumbers
} | Out-File $outfile -Append

Upvotes: 1

Related Questions