带有params *和*函数的Powershell脚本

时间:2013-02-15 20:05:07

标签: powershell params

我想编写一个PowerShell脚本,它接受参数并使用函数。

我试过了:

param
(
  $arg
)

Func $arg;


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

但我得到了这个:

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

很好,我想。我会试着这样做:

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


param
(
  $arg
)

Func $arg;

但是,我得到了这个:

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

我要求的是可行的吗?或者我在请求中是不合理的?

3 个答案:

答案 0 :(得分:19)

脚本中的param块必须是第一个非注释代码。之后,您需要在调用它之前定义该函数,例如:

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

在您的示例中不需要写入输出,因为默认行为是将对象输出到输出流。

答案 1 :(得分:4)

你只需要确保PARAM是你脚本的第一个字符串。

答案 2 :(得分:-3)

您可以将param标签放在函数中..

这样的事情:

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