powershell脚本根据函数调用输出不同

时间:2015-05-20 07:35:07

标签: powershell

我有以下脚本,我无法理解发生了什么:

function foo {
    param(
        [string]$p1,
        [string]$p2
    )

    echo $p1 $p2
}

$a = "hello"
$b = "world"

foo $a $b
foo $a, $b

输出

PS C:\code\misc> .\param_test.ps1
hello
world
hello world

调用函数的两种方式有什么区别?

1 个答案:

答案 0 :(得分:2)

当您在对象之间使用逗号时,它会打印出两个字符串。

PS:> $a="string 1"
PS:> $b="string 2"
PS:> $a,$b
string 1
string 2

在上面的例子中,如果对象与逗号组合在一起,它就变成了一个数组。

PS:> $c=$a,$b
PS:> $c.getType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

因此,在您的情况下,您将数组转换为字符串。

PS:> [string]$s = $c
PS:> $s
string 1 string 2
PS:>

这里解释了逗号的行为。

PS:>help about_Arrays 

For example, to create an array named $A that contains the seven
numeric (int) values of 22, 5, 10, 8, 12, 9, and 80, type:

    $A = 22,5,10,8,12,9,80
相关问题