括号Powershell函数 [英] Parenthesis Powershell functions

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

问题描述



我以这个函数为例

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

如果我使用
Greet Ricardo 5 问候Ricardo5 的作品。
但是当我使用 Greet(Ricardo,5) Greet(Ricardo; 5)失败。



有什么不对?

解决方案

像cmdlet。也就是说,你不需要输入dir(c:\temp)。函数同样将参数作为空格分隔,并且像cmdlet一样支持位置,命名和可选参数,例如:
$ b $ pre $ Greet Recardo 5
Greet -times 5 -name Ricardo

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

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

Greet Ricardo(1 + 4)

伟大的里卡多#请注意$ times默认为5

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

  Greet Ricardo,Lucy,Ethyl(6-1)

所以当你传入像(Ricardo,5)之类的东西时,它被认为是一个包含两个元素的数组的单个参数值Ricardo 5 。这将被传递给 $ name 参数,但是对于 $ times 参数将没有值。



只有在调用.NET方法时才使用括号括起来的参数列表,例如:

 Hello World.Substring(6,3)


How to call function using parameters in powershell with parenthesis.

I have as example this function

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

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.

What is wrong?

解决方案

Functions behaves like cmdlets. That is, you don't type dir(c:\temp). 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 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)

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.

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天全站免登陆