简体   繁体   English

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

[英]Powershell - named parameters and script built-in functions?

I am trying to build a script, that accepts named arguments - but the script also has functions in it... This gives me a problem, that I cannot see how to fix. 我正在尝试构建一个脚本,该脚本接受命名的参数-但是该脚本中也包含函数...这给我带来了一个问题,我看不到如何解决。 The script - c:\\temp\\example.ps1 - looks like: 脚本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

This gives me: 这给了我:

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

How do I fix this - so that named parameters can be used for functions - but also be used in the "main" script (getting the command line arguments when calling the script) ? 如何解决此问题-以便将命名参数用于函数-还可以在“主”脚本中使用(在调用脚本时获取命令行参数)?

Change the order in your script 在脚本中更改顺序

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

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


test -p1 $Hostname

Param section must be at the start of your code Param部分必须在代码的开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM