The Powershell Function Directory

Anybody that has been using Powershell has created a function at some point. A function is simply a named ScriptBlock that can accept parameters. Also, you very likely know that there is a Function provider in Powershell. But I am willing to bet a lot of folks haven't used the provider all that much. If I am wrong, I would love to hear some feedback on the topic.

So here I am going to create a basic function and then we will look at what we can do with the function provider to manipulate it.

   1: 6 >  function foo {"Hello $args"}
   2: 7 >  foo world
   3: Hello world

So now that we have a new function we can cd into the function drive as follows. Notice that now we can get some cool info about the function we just created.

   1: 11 >  cd function:
   2: 12 >  ls foo | fl
   5: Name        : foo
   6: CommandType : Function
   7: Definition  : "Hello $args"

Since we are in the function directory, we can rename a function quite easily.

   1: 15 >  rename-item foo bar
   2: 16 >  bar world
   3: Hello world
   5: 17 >  ls foo
   6: Get-ChildItem : Cannot find path 'foo' because it does not exist.
   7: At line:1 char:3
   8: + ls <<<<  foo
   9: 18 >  ls bar | fl
  12: Name        : bar
  13: CommandType : Function
  14: Definition  : "Hello $args"

There is no longer a function called foo but we do have a function named bar with the exact same definition that foo had originally.

Armed with this information, occasionally I like to take a look at what one of my functions looks like.

To do this all I need is to run get-content on a function, or use the alias cat.

   1: 28 >  cat Function:\Add-Assembly
   2: param($name) return [System.Reflection.Assembly]::LoadWithPartialName($name)
Comments are closed