【问题标题】:Powershell script with params *and* functions带有参数 * 和 * 函数的 Powershell 脚本
【发布时间】:2015-01-12 01:57:08
【问题描述】:

我想写一个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

我的要求可行吗?还是我的要求不合理?

【问题讨论】:

  • powershell 脚本的顺序通常是,1) 参数,2) 函数 3) 函数调用/命令 cmdlet 执行。
  • Christopher Ranney,这是一个很有帮助的总结。如果您将此作为问题发布,我会投赞成票。
  • 如果您愿意,可以投票支持 cmets。 :)

标签: powershell params


【解决方案1】:

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

param
(
  $arg
)

function Func($arg)
{
  $arg
}

Func $arg

Write-Output 在您的示例中是不必要的,因为默认行为是将对象输出到输出流。

【讨论】:

  • 如果我们将该函数定义移动到一个模块中并将其导入我们的机器上,然后像@Tola Odejayi 试图做的那样调用它呢?
  • @FarrukhWaheed 这同样适用于模块。虽然这可能不是典型情况,但 PSM1 可以像常规脚本文件一样定义参数和执行代码(不仅仅是定义函数)。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    你可以把param标签放在函数里面..

    类似这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2017-11-29
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      相关资源
      最近更新 更多