Monday, September 1, 2008

Putting the Fun in Functions

I just wanted to make a quick post to point out two neat features of functions that I left out of the last post since it was getting a little long, piping to functions, and autocomplete for functions.


AutoComplete for Cmdlets and Functions

You're probably used to using the TAB key to autocomplete file names, but have you noticed that you can autocomplete cmdlet and function names, too?  This comes in useful a lot since I don't have all of the standard cmdlets' names memorized yet.  Just start typing the name of a function or cmdlet and hit tab.  If the name that comes up isn't what you're looking for, just keep hitting TAB and you'll cycle through the available options.

For example:

PS C:\>  out-

Will give you, if you keep tabbing:
  • Out-Clipboard
  • Out-Default
  • Out-File
  • Out-GridView (super cool, I didn't know about this one)
  • Out-Host
  • Out-Null
  • Out-Printer
  • Out-String


Piping to Functions

Piping to functions is really easy.  Anything piped to a function is automatically added to an array called $input.  You can just add a loop in your function to cycle through the values in $input and voila!

Take the following example**:

# Get-Count()
# Gets the number of objects in the input pipeline.
#
# Returns:
#   An int with the count
#

function Get-Count () {
  $i = 0;

  foreach ($obj in $input) {
    $i++;
  }

  Write-Output $i
}


** "But Tojo," you're thinking, "Doesn't Measure-Object do the same thing?"  Indeed it does, but it's much slower in my experience because it also has a lot of extra bells and whistles that I don't need if I just want to see how many lines are in a file, etc.

No comments: