括号 Powershell 函数 [英] Parenthesis Powershell functions

查看:20
本文介绍了括号 Powershell 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to call function using parameters in powershell with parenthesis.

我以这个函数为例

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) 它失败了.

If I call the functions using Greet Ricardo 5 or Greet "Ricardo" 5 works. But when I use Greet ("Ricardo",5) or Greet("Ricardo" ; 5) It fails.

怎么了?

推荐答案

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

Functions behaves like cmdlets. That is, you don't type dir(c: emp). Functions likewise take parameters as space separated and like cmdlets, support positional, named and optional parameters e.g.:

Greet Recardo 5
Greet -times 5 -name Ricardo

PowerShell 使用 () 允许您指定如下表达式:

PowerShell uses () to allow you to specify expressions like so:

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

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

You can also specify arrays simple by using a comma separated list e.g.:

Greet Ricardo,Lucy,Ethyl (6-1)

因此,当您传入诸如 ("Ricardo",5) 之类的内容时,它被评估为单个参数值,该值是一个包含两个元素的数组 "Ricardo"5.这将传递给 $name 参数,但是 $times 参数将没有值.

So when you pass in something like ("Ricardo",5) that is evaluated as a single parameter value that is an array containing two elements "Ricardo" and 5. That would be passed to the $name parameter but then there would be no value for the $times parameter.

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

The only time you use a parenthesized parameter list is when calling .NET methods e.g.:

"Hello World".Substring(6, 3)

这篇关于括号 Powershell 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆