November 21st, 2006

How Can I Add a Function to a Windows PowerShell Script?

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I add a function to a Windows PowerShell script?

— TT

SpacerHey, Scripting Guy! AnswerScript Center

Hey, TT. You know, we’re going to do something a little unusual today: we aren’t going to mention the fact that the University of Washington defeated Washington State University in the annual Apple Cup football game. Granted, that’s the kind of thing we typically would bring up in this column. As it turns out, however, the Scripting Guys’ manager is an alumnus of Washington State University, and, in deference to him, we’re not going to mention the fact that UW won, or note that the Huskies now lead the all-time series 64 wins to 29 wins. After all, it’s bad enough that the poor guy had to attend WSU; there’s no need for us to add insult to injury.

Instead, we’re going to do something really unusual and just talk about scripting today. How can you add a function to a Windows PowerShell script? Well, here’s one way:

function multiplynumbers
    {$args[0] * $args[1]}
multiplynumbers 446 282

As you can see, there really isn’t much to this process. To create a function we simply call the function keyword followed by the name of the function; in this case, we’re naming our function multiplynumbers. Inside a pair of curly braces we then include the code we want the function to carry out. In this case that’s pretty simple: all we’re going to do is multiply the two values provided as function parameters. Hence this block of code:

{$args[0] * $args[1]}

That’s a good point: the $args variable typically does represent the command-line arguments supplied when you start a script. In this case, however, $args serves a dual purpose. The variable – when used outside the function – still contains any command-line arguments used when the script was started. Inside the function, however, $args represents the parameters supplied when calling the function. As you might expect, $args[0] represents the first parameter in the set while $args[1] represents the second parameter. It’s a tad bit confusing, but it works: the function uses the parameters passed to it, and the command-line arguments are still available.

Speaking of parameters, to call the function all we have to do is specify the function name followed by those parameters. In this case, that means typing multiplynumbers followed by the two numbers that we want to multiply:

multiplynumbers 446 282

All of that results in a script that echoes back the following:

125772

Pretty cool, huh?

The main thing to watch out for here is that you need to define the function before you call it. Suppose we didn’t do that, suppose we tried running this script instead:

multiplynumbers 446 282
function multiplynumbers
    {$args[0] * $args[1]}

Is the preceding script going to multiply the numbers 446 and 282 for us? Nope. Instead, it’s going to give us the following error message:

The term 'multiplynumbers' is not recognized as a cmdlet, function, operable program, or script file.
Verify the term and try again.
At C:\scripts\test.ps1:1 char:16
+ multiplynumbers  <<<< 446 282

Why the error message? One simple reason: the script called the function before the function had been defined. Define your functions first, right at the beginning of the script, and you’ll avoid these kinds of problems.

Now here’s a neat trick for you. Instead of defining the function in your script you can define it at the command prompt. Try this: type the following at the Windows PowerShell command prompt and then press ENTER:

function multiplynumbers {$args[0] * $args[1]}

So what, you ask? Well, believe it or not you now you have a function that you can call from any script, without having to define the function within the script itself. That means the following single-line script will return the value 125772:

multiplynumbers 446 282

In fact, you can even type the above command at the command prompt and you’ll get back the correct answer. Give it a try and see for yourself.

We told you that was a neat little trick.

Of course, this function will last only as long as your current Windows PowerShell session. If you’d like multiplynumbers to be a permanent addition to Windows PowerShell then add the function to your Windows PowerShell profile. To do that, type notepad $profile to bring up your default profile, add the function call, and then save the profile.

It’s so easy even a Cougar could do it.

That should get you started, TT. And you’re right: many UW alums would take the opportunity to gloat a little here, especially since – based on their abysmal performance a week ago – no one expected the Huskies to give the Cougars much of a battle, let alone win the game. In fact, this would typically be the time when Huskies would taunt the Cougars, usually by insinuating that the very best job a graduate of WSU could aspire to would be grocery bagger or fast food restaurant worker. But that won’t happen today. After all, the Scripting Guys’ boss doesn’t bag groceries or work at a fast food restaurant; instead, he’s a manager at Microsoft.

Which, it goes without saying, is nowhere near as good a job as bagging groceries. But when you’re a graduate of WSU you pretty much have to take whatever job you can get, don’t you?

Go Huskies!

Author

0 comments

Discussion are closed.