Possible Duplicate:
What does $_ mean in powershell?
I have already seen someone else's question and answer on the same subject but for me it does not answer the question.
I know how to use Select-Object, Where-Object, ForEach-Object etc and pass a script block in, for example:
dir | ForEach-Object { $_.Name }
which returns an array of all file names in the current directory.
This is similar to C#'s Select extension method:
Dir.Select(x => x.Name)
However, the above C# is easily understandable because we are passing a function to the Select method which then executes it for each element in the list.
However, the equivalent in PowerShell:
dir | ForEach-Object { param($x) $x.Name }
does not return anything. However
& { param($x) $x.Name } (dir)[0]
works as expected.
Can someone please explain the magic of $_ to someone familiar to C# but not the world of scripting? It is a special keyword? Can it be only be used in script blocks which are passed into cmdlets? How do you invoke one without piping one to ForEach-Object (or any other cmdlet)? i.e:
& { $_.Name } (dir)[0]
?