2013-02-15 75 views
5

我想编写一个接受参数并使用函数的powershell脚本。带参数*和*函数的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 

就是我要求的可行?或者我的要求不合理?

+2

PowerShell脚本的顺序通常是1)Params,2)函数3)执行函数调用/有序cmdlet。 – 2013-02-15 21:13:29

+0

克里斯托弗兰尼,这是一个有益的总结。如果您已将此作为问题发布,我会投票表决。 – 2013-02-17 03:03:39

+0

如果你的心愿意,你可以投票评论。 :) – 2013-02-19 16:10:16

回答

19

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

param 
(
    $arg 
) 

function Func($arg) 
{ 
    $arg 
} 

Func $arg 

写产出是你的榜样不必要的,因为默认的行为是输出对象到输出流。

+0

如果我们将这个函数定义移动到一个模块中,并将其导入到我们的机器上,那么将@Tola Odejayi试图执行的操作称为? – 2013-09-19 12:12:13

+0

@FarrukhWheheed这同样适用于模块。虽然不是典型的情况,但PSM1可以像常规脚本文件一样定义参数并执行代码(不仅仅是定义fucnctions)。 – 2013-09-19 14:42:55

-2

你可以把param标签里面的功能..

事情是这样的:

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

所有你需要学联确保参数是脚本的第一个字符串。