0

I have the following script, and I can't understand what is going on:

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

    echo $p1 $p2
}

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

foo $a $b
foo $a, $b

The output is

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

What is the difference between the two ways the function is called?

deostroll
  • 11,661
  • 21
  • 90
  • 161

1 Answers1

2

When you use comma between the objects, it prints out both strings.

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

In above case, if the objects are combined with comma, it becomes an array.

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

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

So in your case, you are converting an array into a string.

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

Behavior of comma is explained here.

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
hysh_00
  • 819
  • 6
  • 12