Did you ever find yourself knowing that you had written a function but you couldn’t remember which module you put it in? If you have the module imported, you can find out with this:
dir function:functionname | select Name,ModuleName
Note that I am defiantly using the “dir” alias for get-childitem even though everyone says not to. I’ll be a rulebreaker again later on in this post as you’ll see.
If you ever wanted to know the definition of a function you can use the “definition” property:
dir function:functionname | select -expand Definition
I recently put these 2 together in a helper function I call “def”
function def{ param($funcname) $func=dir function:$funcname if($func.ModuleName){ Write-host "$func is defined in module $($func.ModuleName)" } write-host $Func.definition }
Here you’ll see my rebellious ways in 2 different strains:
- I defined a function without using the verb-noun convention
- I used write-host to provide output from a function
For what it’s worth, I am very fond of the verb-noun naming convention. I was tempted to name the function “show-commanddefinition” and give it an alias of “def”, but I doubt I’d ever use the full name.
Also, I completely agree with not using write-host to provide output from functions. Doing so makes the function in question a dead-end as far as PowerShell goes. In this case, I used it because I was providing 2 different kinds of output (the module name and the definition of the function) and writing those to the output stream wouldn’t help much. I could have defined an object with those 2 properties, or even just used select-object to whittle down the command object to those 2, but then the default display would have made presented a tabular view which probably would have truncated the definition. This function wasn’t meant to be consumed by other functions, it was meant for me to look at the output. Thus, write-host
was the right choice. Jeff Hicks is correct, though, every time you use write-host in a function (let’s say a “real function”), %deity% kills a puppy.
Fortunately for everyone I know, that’s about as rebellious as I get.
Let me know what you think.
Mike