【问题标题】:Parenthesis Powershell functions括号 Powershell 函数
【发布时间】:2012-06-17 00:33:23
【问题描述】:

如何在powershell中使用带括号的参数调用函数。

我有这个函数的例子

function Greet([string]$name , [int]$times)
{
    for ([int]$i = 1; $i -le $times;$i++)
    {
        Write-Host Hiiii $name
    }
}

如果我使用 Greet Ricardo 5Greet "Ricardo" 5 有效。 但是当我使用Greet ("Ricardo",5)Greet("Ricardo" ; 5) 时会失败。

怎么了?

【问题讨论】:

  • 没有括号有什么问题?
  • 什么都没有。我想知道他们如何创建使用括号的函数(cmd-let)
  • 例如 $ACL.SetAccessRule $Rule 没有括号就不能工作。

标签: function powershell


【解决方案1】:

函数的行为类似于 cmdlet。也就是说,您不需要键入 dir(c:\temp)。函数同样将参数作为空格分隔,类似于 cmdlet,支持位置参数、命名参数和可选参数,例如:

Greet Recardo 5
Greet -times 5 -name Ricardo

PowerShell 使用 () 允许您像这样指定表达式:

function Greet([string[]]$names, [int]$times=5) {
    foreach ($name in $names) {
        1..$times | Foreach {"Hi $name"}
    }
}

Greet Ricardo (1+4)

Great Ricardo    # Note that $times defaults to 5

您还可以使用逗号分隔的列表简单地指定数组,例如:

Greet Ricardo,Lucy,Ethyl (6-1)

因此,当您传入像 ("Ricardo",5) 这样的东西时,它被评估为单个参数值,该参数值是一个包含两个元素 "Ricardo"5 的数组。这将被传递给$name 参数,但$times 参数将没有值。

您唯一使用带括号的参数列表是在调用 .NET 方法时,例如:

"Hello World".Substring(6, 3)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多