5

I want to write a powershell script that takes in params and uses functions.

I tried this:

param
(
  $arg
)

Func $arg;


function Func($arg)
{
  Write-Output $arg;
}

but I got this:

The term 'Func' is not recognized as the name 
of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At func.ps1:6 char:5
+ Func <<<<  $arg;
    + CategoryInfo          : ObjectNotFound: (Func:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Fine, I thought. I'll try this instead:

function Func($arg)
{
  Write-Output $arg;
}


param
(
  $arg
)

Func $arg;

But then, I got this:

The term 'param' is not recognized as the name 
of a cmdlet, function, script file, or operable program. 
Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again.
At C:\Users\akina\Documents\Work\ADDC\func.ps1:7 char:10
+     param <<<<
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Is what I'm asking for doable? Or am I being unreasonable in my request?

Tola Odejayi
  • 3,019
  • 9
  • 31
  • 46

3 Answers3

19

The param block in a script has to be the first non-comment code. After that, you need to define the function before you invoke it e.g.:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

The Write-Output is unnecessary in your example since the default behavior is to output objects to the output stream.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • And what if we move that function definition into a Module and import that on our machine, then call that as @Tola Odejayi is trying to do? – Farrukh Waheed Sep 19 '13 at 12:12
  • @FarrukhWaheed The same applies to a module. Though it isn't probably the typical case, a PSM1 can define parameters and execute code (not just define fucnctions) just like a regular script file. – Keith Hill Sep 19 '13 at 14:42
4

All you need ius to make sure PARAM is first string of your script.

-3

You can put the param tag inside the function..

Something like this:

function func($avg)
{
    param
    (
         $avg
    )
}
Lodder
  • 19,758
  • 10
  • 59
  • 100