{"id":65993,"date":"2006-11-21T13:56:00","date_gmt":"2006-11-21T13:56:00","guid":{"rendered":"https:\/\/blogs.technet.microsoft.com\/heyscriptingguy\/2006\/11\/21\/how-can-i-add-a-function-to-a-windows-powershell-script\/"},"modified":"2006-11-21T13:56:00","modified_gmt":"2006-11-21T13:56:00","slug":"how-can-i-add-a-function-to-a-windows-powershell-script","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-add-a-function-to-a-windows-powershell-script\/","title":{"rendered":"How Can I Add a Function to a Windows PowerShell Script?"},"content":{"rendered":"<p><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Question\" border=\"0\" alt=\"Hey, Scripting Guy! Question\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/q-for-powertip.jpg\" width=\"34\" height=\"34\"><\/p>\n<p>Hey, Scripting Guy! How can I add a function to a Windows PowerShell script?<\/p>\n<p>&#8212; TT<\/p>\n<p><img decoding=\"async\" border=\"0\" alt=\"Spacer\" src=\"https:\/\/devblogs.microsoft.com\/scripting\/wp-content\/uploads\/sites\/29\/2019\/05\/spacer.gif\" width=\"5\" height=\"5\"><img decoding=\"async\" class=\"nearGraphic\" title=\"Hey, Scripting Guy! Answer\" border=\"0\" alt=\"Hey, Scripting Guy! Answer\" align=\"left\" src=\"https:\/\/devblogs.microsoft.com\/wp-content\/uploads\/sites\/29\/2019\/02\/a-for-powertip.jpg\" width=\"34\" height=\"34\"><a href=\"http:\/\/go.microsoft.com\/fwlink\/?linkid=68779&amp;clcid=0x409\"><img decoding=\"async\" class=\"farGraphic\" title=\"Script Center\" border=\"0\" alt=\"Script Center\" align=\"right\" src=\"http:\/\/img.microsoft.com\/library\/media\/1033\/technet\/images\/scriptcenter\/ad.jpg\" width=\"120\" height=\"288\"><\/a><\/p>\n<p>Hey, TT. You know, we\u2019re going to do something a little unusual today: we aren\u2019t going to mention the fact that the University of Washington defeated Washington State University in the annual Apple Cup football game. Granted, that\u2019s the kind of thing we typically <i>would<\/i> bring up in this column. As it turns out, however, the Scripting Guys\u2019 manager is an alumnus of Washington State University, and, in deference to him, we\u2019re 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\u2019s bad enough that the poor guy had to attend WSU; there\u2019s no need for us to add insult to injury.<\/p>\n<p>Instead, we\u2019re going to do something <i>really<\/i> unusual and just talk about scripting today. How can you add a function to a Windows PowerShell script? Well, here\u2019s one way:<\/p>\n<pre class=\"codeSample\">function multiplynumbers\n    {$args[0] * $args[1]}\nmultiplynumbers 446 282\n<\/pre>\n<p>As you can see, there really isn\u2019t much to this process. To create a function we simply call the <b>function<\/b> keyword followed by the name of the function; in this case, we\u2019re naming our function <i>multiplynumbers<\/i>. Inside a pair of curly braces we then include the code we want the function to carry out. In this case that\u2019s pretty simple: all we\u2019re going to do is multiply the two values provided as function parameters. Hence this block of code:<\/p>\n<pre class=\"codeSample\">{$args[0] * $args[1]}\n<\/pre>\n<p>That\u2019s a good point: the <b>$args<\/b> variable typically <i>does<\/i> represent the command-line arguments supplied when you start a script. In this case, however, $args serves a dual purpose. The variable \u2013 when used outside the function \u2013 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, <b>$args[0]<\/b> represents the first parameter in the set while <b>$args[1]<\/b> represents the second parameter. It\u2019s a tad bit confusing, but it works: the function uses the parameters passed to it, and the command-line arguments are still available.<\/p>\n<p>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 <i>multiplynumbers<\/i> followed by the two numbers that we want to multiply:<\/p>\n<pre class=\"codeSample\">multiplynumbers 446 282\n<\/pre>\n<p>All of that results in a script that echoes back the following:<\/p>\n<pre class=\"codeSample\">125772\n<\/pre>\n<p>Pretty cool, huh?<\/p>\n<p>The main thing to watch out for here is that you need to define the function before you call it. Suppose we didn\u2019t do that, suppose we tried running this script instead:<\/p>\n<pre class=\"codeSample\">multiplynumbers 446 282\nfunction multiplynumbers\n    {$args[0] * $args[1]}\n<\/pre>\n<p>Is the preceding script going to multiply the numbers 446 and 282 for us? Nope. Instead, it\u2019s going to give us the following error message:<\/p>\n<pre class=\"codeSample\">The term 'multiplynumbers' is not recognized as a cmdlet, function, operable program, or script file.\nVerify the term and try again.\nAt C:\\scripts\\test.ps1:1 char:16\n+ multiplynumbers  &lt;&lt;&lt;&lt; 446 282\n<\/pre>\n<p>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\u2019ll avoid these kinds of problems.<\/p>\n<p>Now here\u2019s 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:<\/p>\n<pre class=\"codeSample\">function multiplynumbers {$args[0] * $args[1]}\n<\/pre>\n<p>So what, you ask? Well, believe it or not you now you have a function that you can call from <i>any<\/i> script, without having to define the function within the script itself. That means the following single-line script will return the value 125772:<\/p>\n<pre class=\"codeSample\">multiplynumbers 446 282\n<\/pre>\n<p>In fact, you can even type the above command at the command prompt and you\u2019ll get back the correct answer. Give it a try and see for yourself. <\/p>\n<p>We told you that was a neat little trick.<\/p>\n<p>Of course, this function will last only as long as your current Windows PowerShell session. If you\u2019d like <i>multiplynumbers<\/i> to be a permanent addition to Windows PowerShell then add the function to your Windows PowerShell profile. To do <i>that<\/i>, type <b>notepad $profile<\/b> to bring up your default profile, add the function call, and then save the profile. <\/p>\n<p>It\u2019s so easy even a Cougar could do it.<\/p>\n<p>That should get you started, TT. And you\u2019re right: many UW alums <i>would<\/i> take the opportunity to gloat a little here, especially since \u2013 based on their abysmal performance a week ago \u2013 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\u2019t happen today. After all, the Scripting Guys\u2019 boss doesn\u2019t bag groceries or work at a fast food restaurant; instead, he\u2019s a manager at Microsoft.<\/p>\n<p>Which, it goes without saying, is nowhere <i>near<\/i> as good a job as bagging groceries. But when you\u2019re a graduate of WSU you pretty much have to take whatever job you can get, don\u2019t you?<\/p>\n<p>Go Huskies!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey, Scripting Guy! How can I add a function to a Windows PowerShell script? &#8212; TT Hey, TT. You know, we\u2019re going to do something a little unusual today: we aren\u2019t going to mention the fact that the University of Washington defeated Washington State University in the annual Apple Cup football game. Granted, that\u2019s the [&hellip;]<\/p>\n","protected":false},"author":595,"featured_media":87096,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[51,3,4,45],"class_list":["post-65993","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scripting","tag-getting-started","tag-scripting-guy","tag-scripting-techniques","tag-windows-powershell"],"acf":[],"blog_post_summary":"<p>Hey, Scripting Guy! How can I add a function to a Windows PowerShell script? &#8212; TT Hey, TT. You know, we\u2019re going to do something a little unusual today: we aren\u2019t going to mention the fact that the University of Washington defeated Washington State University in the annual Apple Cup football game. Granted, that\u2019s the [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65993","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/users\/595"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/comments?post=65993"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/posts\/65993\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media\/87096"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/media?parent=65993"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/categories?post=65993"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/scripting\/wp-json\/wp\/v2\/tags?post=65993"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}