Monday, 15 November 2010

Powershell: Catching an unspecified number of arguments into an array

I recently had the need for creating a command to be executed on an unspecified number of objects, and being picky regarding the command syntax, I wanted it to be called in the "usual" way, like:

My-Command namedParameter file1 file2 ... file
I.e. the user should not have to know that the list of objects (in this case, files) had to be specified as an array.

This was fairly easy in Powershell, making use of the $MyInvocation predefined variable: simply define those parameters you want as named parameters, and catch the 'rest' into an array.
function My-Command {
   param ($namedParameter)
   #Catch the items to be labelled from the unbound arguments
   if ($MyInvocation.UnboundArguments.Count -gt 0) {
      [string[]]$items = $MyInvocation.UnboundArguments
   }
   else
   {
      [string[]]$items = (($pwd).toString())
   }
   ...
}
In this case, if no unbound arguments are given, the $items array at least gets one value consisting of the current directory path, but you could easily replace that with for example a throw()-statement instead.

No comments:

Post a Comment