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 an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus

SharePoint Watch

Sign up for our newsletter.

I agree to this site's Privacy Policy.