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?

2

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.