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?

3
  • 2
    The order of a powershell script is typically, 1) Params, 2) Functions 3) Function calls/ordered cmdlets to execute. Commented Feb 15, 2013 at 21:13
  • Christopher Ranney, that's a helpful summarisation. If you had posted this as a question, I would have voted it up. Commented Feb 17, 2013 at 3:03
  • You can vote up comments if your heart so desires. :) Commented Feb 19, 2013 at 16:10

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.
4

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

Comments

-3

You can put the param tag inside the function..

Something like this:

function func($avg)
{
    param
    (
         $avg
    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.