Line Count with PowerShell
Starting to get the hang of PowerShell. Today I wanted to quickly count the number of lines in some source code. There's a simple implementation and then there's a better one. In the end I settled on:
$count=0;gci . -i *.cs,*.cpp,*.h -r | %{$count += [System.IO.File]::ReadAllLines($_.FullName).Count};$count
Which is quick to type and fast enough for me, although as the links show you can butter it up and put it in a .ps1 file if you want too.
Puzzle Time!
Here's a little PowerShell test that I have to admit I had to get some help with. Why does:
1,2,3 | %{$_}
Produce the output:
1
2
3
But this produces nothing:
$code={%{$_}}
1,2,3 | &$code
Remember, & executes a script block and % is just an alias for Foreach-Object.
Want the answer?
It's a question of scope. In the second example &$code is equivalent to &{%{$_}}. The extra {}'s puts $_ in a different script variable scope, one in which it has not been initialized. To get things working again, you need to reattach it to the pipeline input, like so:
$code={$input | %{$_}}
1,2,3 | &$code