Powershell 2.0 Param关键字错误

Joh*_*gle 42 powershell

我正在运行Windows 7 RTM.默认情况下安装Powershell 2.0.我正在使用优秀的Windows Powershell ISE来编辑我的脚本.我有以下脚本:

Param($p)
Param($d)
echo $p $d
Run Code Online (Sandbox Code Playgroud)

我将脚本保存为SayItAgain.ps1.当我尝试从交互式shell运行此脚本时,如下所示:

./SayItAgain -p "Hello"
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

At C:\users\cius\Code\powershell\SayItAgain.ps1:2 char:6
+ Param <<<< ($destination)
    + CategoryInfo          : ObjectNotFound: (Param:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
Run Code Online (Sandbox Code Playgroud)

这是一个已知问题还是我只是错误使用它?

Dav*_*ker 74

如果您param($p)不是脚本中可能导致Param错误的第一行.

确保你param($p)是第一线.

  • 我仍然感到惊讶的是“必须是文件的第一行”是在新语言中持续存在的首选解决方案。由于只能有一个“第一行”,所以它看起来就像是一个黑客。 (4认同)
  • 这很可能是问题,但第一个非注释行就足够了. (3认同)
  • 虽然乔恩·英格尔接受的答案可以解决他的问题。我觉得这很可能是其他程序员会遇到的关于“参数”的问题,并提供了确切的解决方案。谢谢@大卫。 (2认同)
  • 如果只有错误消息可以提到这一点! (2认同)

Joh*_*gle 38

我已经解决了这个问题.我为我不完整和不一致的信息道歉.我已经纠正了问题的描述以使其准确.我感谢你的帮助.

问题的根源是我多次错误地使用Param关键字.正确的用法是在单个Param声明中声明多个参数,如下所示:

Param($p, $d)
Run Code Online (Sandbox Code Playgroud)

Windows Powershell帮助文章"about_Functions"中介绍了此用法.