使用循环将参数传递给函数

马基吉

我有一个功能

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 循环来传递每一个来打印我的名字是马克。你好,我的名字不是马克。你好!

我很感激任何帮助。

马蒂亚斯·R·杰森

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

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()块中定义的字符串

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章