Tola Odejayi
Tola Odejayi

Reputation: 3059

Powershell script with params *and* functions

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?

Upvotes: 5

Views: 19257

Answers (3)

Anton Chernysh
Anton Chernysh

Reputation: 41

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

Upvotes: 4

user3119242
user3119242

Reputation: 1

You can put the param tag inside the function..

Something like this:

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

Upvotes: -3

Keith Hill
Keith Hill

Reputation: 201822

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.

Upvotes: 20

Related Questions