How to embed a pipeline operator within a Powershell filter?
I'm trying to make a filter that groups by file extension. With the group operator, it's easy:
$fileList | group { [io.path]::getextension($_) }
I'd like to make the above into a filter to save some typing, so I can do this instead:
$fileList | group-by-extension
But I'm having trouble figuring out the right syntax. These obviously don't work, for example:
filter group-by-extension { $_ | group { [io.path]::getextension($_) } }
function group-by-extension { $_ | group { [io.path]::getextension($_) } }
How do you write a function that receives a pipe and returns it running through 开发者_运维问答another filter?
Filters act on each individual object that comes through the pipeline. In your code, you are basically grouping one object at a time. What you need to do is gather all your objects together, and then group them. You can use a function with the BEGIN, PROCESS, and END Blocks.
function GroupBy-Extension {
BEGIN {$all = @() }
PROCESS { $all += $_}
END {$all | group extension}
}
I'm not sure if you're specifically wanting to sort by property (extension in this case) or get better with pipes. On the assumption that it's the sorting you're trying to get into, please allow me to show you the simplest way to do it.
Get-ChildItem | Sort-Object extension
Here's a link about it: http://technet.microsoft.com/en-us/library/ee176968.aspx
Since this takes more than one keyword to accomplish, it cannot be aliased. It must be written as a function. I like two or three letter command names. Unix is like that and it makes typing simpler. Maybe make the function take the parameter by which you'd like to sort, with that parameter being whatever Sort-Object takes. So, I'll call it gcis for Get-ChildItem-Sorted. The syntax might be "gcis extension"
.
Or, if you're like me, you don't even like putting in that one parameter. (I'm really lazy at the command-line). Call the function as gcie(for sort by extension), gcit(for time), gcis(for size) or things like that. You can build the function with name overloading to behave differently based on what you call it. Or, you can make a separate function for each one, if you aren't good with overloading.
I hope this helps and answers what you asked.
Regards, Rodney Fisk
精彩评论