Prof. Powershell

Function Fun

Have a blast stringing along functions and reusing them.

Your Windows PowerShell session has a wealth of functionality. In addition to cmdlets, PowerShell loads a number of functions when you launch your console. If you define additional functions, from the command prompt, through your profile or by dot-sourcing a script, these functions are also ready for you to use.

To see what functions are available, simply peruse your Function: drive, like this:

PS C:\ dir function:

To examine a specific function, use Get-ChildItem.

PS C:\ dir function:mkdir


That doesn't show much information. So try this:

PS C:\ dir function:mkdir | Select * | More

Now we're talking. I pipe the result to more because a lot of information might scroll by pretty quickly; although usually I'm only interested in a function's definition. That is easy to get since definition is merely a property:

PS C:\ (dir function:mkdir).Definition

Here's where this can come in handy. Suppose you create a new function in the shell:

PS C:\> function dirdate {
>> param ([string]$path=".",
>>        [switch]$recurse,
>>        [switch]$descending )if ($recurse) {
>>        $files= dir $path -recurse
>>        }
>>   else {
>>   $files=dir $path
>>   }
>>
>> if ($descending) {
>>   $files | sort LastwriteTime -descending
>>   }
>> else {
>>   $files
>>   }
>> }

Now you'd like to save this function so you can re-use it in future PowerShell sessions. Here's a one-liner that will get the job done:

PS C:\> (dir function:dirdate).definition.Split("'n")| foreach -begin {"Function DirDate { 'n" | out-file dirdate.ps1} -Process {$_ | out-file dirdate.ps1 -append} -end {"}" | out-file dirdate.ps1 -append}

I can create a working script with less code but the formatting leaves something to be desired. This command gets the function definition, which is normally stored as a string. I split it at the new line and pipe this to ForEach-Object. Before I process anything, I create the first part of the file -- that is, the function keyword and name. Then each line from the definition is appended to the file. After all lines have been processed I append the closing “}”. Now, wasn't that fun?


About the Author

Jeffery Hicks is a Microsoft MVP and an IT veteran with almost 20 years of experience, much of it spent as an IT consultant specializing in Windows server technologies. He works today as an independent author, trainer and consultant. His latest book is Managing Active Directory with Windows PowerShell 2.0: TFM (SAPIEN Press 2011). Follow Jeff on Twitter and on his blog.

Reader Comments:

Add Your Comment Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Comment:
Please type the letters/numbers you see above