Prof. Powershell

A Defining Moment

The beauty of PowerShell is simplifying the oft-repeated task. Here's an example where you can create functions on the fly for common troubleshooting.

In Windows PowerShell, a function is a self-contained collection of PowerShell expressions. Almost always a function serves as a way to modularize a task so you don't have to manually re-create the commands every time. Let's say you need to run this command more than once a day because you're troubleshooting a problem:

get-eventlog -LogName System -ComputerName Server01 -EntryType Error -newest 10 | select Timewritten,Source,Message,machinename

That's a lot to type and you'll most likely flub it more than once. Instead, just create a function on the fly:

PS C:\> Function Get-Errors {get-eventlog -LogName System -ComputerName Server01 -EntryType Error -newest 10 | select Timewritten,Source,Message,machinename }

Now you can simply type Get-Errors to run this command:

PS C:\> get-errors | out-file report.txt

But PowerShell comes with a number of its own functions which you can see by getting a directory listing of the Function: PSDrive:

PS C:\> dir function:

You may be wondering how some of these work. Well, when you ran the listing, what you are seeing is a FunctionInfo object which has a property called Definition. If the definition is simple and short, you'll see it. But for the rest, you'll need to grab the complete property:

PS C:\> dir function:mkdir | Select-Object -ExpandProperty Definition

If you run this you'll see the definition of the mkdir function that ships with Windows PowerShell. A related alternative is to use Get-Command:

PS C:\> get-command mkdir | Select-Object -ExpandProperty Definition

Or you can even simplify this further:

PS C:\> (get-command mkdir).Definition

Hey, why don't we create a function on the fly to return function definitions?

PS C:\> function Get-Definition {param ([string]$name) (get-command $name).definition}

This function accepts a name as a parameter. Try this and you should get the function code:

PS C:\> Get-Definition disable-psremoting

Or let's gaze at our inner navel:

PS C:\> get-definition get-definition

If you'd like to learn more, including how to save functions you've created on the fly, be sure to go here.

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 Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular