Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 528
Tola Odejayi Avatar asked Feb 15 '13 20:02

Tola Odejayi


2 Answers

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.

like image 172
Keith Hill Avatar answered Sep 21 '22 19:09

Keith Hill


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

like image 43
Anton Chernysh Avatar answered Sep 22 '22 19:09

Anton Chernysh