tags:

views:

896

answers:

4
    PS C:\Projects> 
    get-childitem  -recurse 
 |  where { $_.Extension -eq ".csproj" }
 | foreach { Get-Content $_.FullName 
          | foreach { $_.Length } }

This prints the line size of every line in a csproj (pretty pointless true). How can I also output a outer variable (so to speak) when I've dived further. So for example let's say for pointeless reasons I wanted to have it print the filename too so I would get:

Dog.csproj: 10 Dog.csproj: 50 Dog.csproj: 4 Cat.csproj: 100 Cat.csproj: 440

I figure I want to do something like this but this does not work obviously, (and yes the example is pointless)

  PS C:\Projects> 
        get-childitem  -recurse 
     |  STORE THIS IN $filename | where { $_.Extension -eq ".csproj" }
     | foreach { Get-Content $_.FullName 
              | foreach { $filename ":"  $_.Length } }

I played with tee-object and outputvariable but I'm a bit lost. If a powershell guru could answer it would help, also if you could recommend a book or resource that explains the language syntax fundamentals rather than API monkey stuff of COM/WMI/VB etc.. (that seems most of what I came across) it would be most appreciated. Thanks

A: 

get-childitem -recurse -filter .csproj | select @{n="FileName";e={$.FullName}},@{n="Lines";e={ $(cat $_.FullName).count}}

It gives an output like:

FileName Lines -------- ---------- D:\Scripts\test1.csproj 867 D:\Scripts\test2.csproj 1773

Shay Levy
A: 

Thanks Shay,

Your example produces a relevant output but not what I'm looking for, in my example I'd print the filename along side the count for each line. Its pretty pointless example but essentially we've moved further on from an FileInfo object being passed along the pipe to now a String object (representing each line), and now I want to reference back to FileInfo that was further back in the pipe, if that makes any sense.

mattcodes
+1  A: 

How about:

dir -r -fo .csproj | select @{n="FileName";e={$.FullName}},@{n="LineLong";e={ cat $.fullName | foreach {$.length}}}

Shay Levy
+4  A: 

This the straightforward way:

`gci . -r "*.csproj" | % { $name = $_.name; gc $_.fullname |
         % { $name + ": " + $_.length }  }`

If you don't yet know the abbreviations, that is equivalent to:

`Get-ChildItem . -recurse "*.csproj" | 
      foreach { $name = $_.name; Get-Content $_.fullname | 
      foreach { $name + ": " + $_.length }  }`

As for a book recommendation, it has to be Bruce Payette's book: http://www.amazon.com/Windows-PowerShell-Action-Bruce-Payette/dp/1932394907

Mike

Mike