Powershell script with parameters * and * functions

I want to write a powershell script that takes parameters 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

Good, I thought. I will 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 this what I ask you to do? Or am I unfounded in my request?

+5
source share
3 answers

The param block in the script should be the first code without comment. After that, you need to define the function before calling it, for example:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

In your example, there is no need to write-output, since the default behavior is to output objects to the output stream.

+19
source

All you need is ius to make sure that PARAM is the first line of your script.

+3
source

param .

- :

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

All Articles