【问题标题】:Passing parameters to a function using loop使用循环将参数传递给函数
【发布时间】:2017-10-30 23:45:00
【问题描述】:

我有一个功能

Function newFunction($1, $2, $3)
{
    $1 + $2 + $3
}

Param (
    [string]$intro= 'My Name is ',
    [string]$name= 'Mark. ',
    [string]$greeting= 'Hello'
    )

它可以运行。 newFunction $intro $name $greeting

导致。 我的名字叫马克。你好

我想做的是某种存储多个参数并将它们传递给函数的方法(下一部分中的这种语法可能是错误的,但希望你明白这一点。

Param ({
    [string]$intro= 'My Name is ',
    [string]$name= 'Mark. ',
    [string]$greeting= 'Hello'
    }{
    [string]$intro= 'My Name is ',
    [string]$name= 'not Mark. ',
    [string]$greeting= 'Howdy!'
    }

我怎样才能得到一个 for 循环来传递这些中的每一个来打印 我的名字叫马克。你好 我的名字不是马克。你好!

感谢您的帮助。

【问题讨论】:

    标签: function powershell for-loop parameters parameter-passing


    【解决方案1】:

    让我们从一个完整的函数定义开始:

    function New-Greeting
    {
        param(
            [string]$Intro = "My name is:",
            [string]$Name = "Mark",
            [string]$Greeting = "Hello!"
        )
    
        return "$Greeting $Intro $Name"
    }
    

    然后,您需要将参数参数从调用范围传递给函数,而不是在函数定义内。

    例如带有变量Name参数值:

    $Names = "Mark","John","Bobby"
    foreach($Name in $Names){
        New-Greeting -Name $Name
    }
    

    将返回:

    Hello! My name is: Mark
    Hello! My name is: John
    Hello! My name is: Bobby
    

    如果您想要多组变量参数,请考虑将它们存储在哈希表中,然后将它们分解,如下所示:

    # Define array of hashtables
    $GreetingArguments = @(
        @{
            Intro = "They call me"
            Name = "Mark"
            Greeting = "Howdy!"
        },@{
            Name = "John"
            Greeting = "Good morning!"
        },@{
            Intro = "I go by: "
            Name = "Bobby"
        }
    )
    
    foreach($Greeting in $GreetingArguments){
        # "splat" the individual hashtables from the array
        New-Greeting @Greeting
    }
    

    导致:

    Howdy! They call me Mark
    Good morning! My name is: John
    Hello! I go by: Bobby
    

    如您所见,每当您传递参数时,New-Greeting 默认为param() 块中定义的字符串

    【讨论】:

      猜你喜欢
      • 2015-11-10
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多