Powershell - 命名参数和脚本内置函数?

时间:2015-08-13 12:21:59

标签: powershell

我正在尝试构建一个接受命名参数的脚本 - 但脚本中也有函数...这给我一个问题,我看不出如何修复。 脚本--c:\ temp \ example.ps1 - 看起来像:

function test
{
 param($p1)
 write-host $p1
}

param(
 [parameter(mandatory=$false)]
 [switch]$EnableOption,
 [parameter(mandatory=$false)]
 [string]$Hostname
)

test -p1 $Hostname

这给了我:

param : 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:\Temp\example.ps1:7 char:1
+ param(
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

如何修复此问题 - 以便命名参数可以用于函数 - 但也可以在“main”脚本中使用(在调用脚本时获取命令行参数)?

1 个答案:

答案 0 :(得分:3)

更改脚本中的顺序

param(
 [parameter(mandatory=$false)]
 [switch]$EnableOption,
 [parameter(mandatory=$false)]
 [string]$Hostname
)

function test
{
 param($p1)
 write-host $p1
}


test -p1 $Hostname

Param部分必须位于代码的开头

相关问题