0

I have created the following to get understanding of how a variable array is passed to a function:

# Define array
[array]$Global:P_sourceHostName = @()
[array]$Global:P_destinationHostName = @()

# Add string values to source array
$global:P_sourceHostName = "ABC"
$global:P_sourceHostName += "DEF"
$global:P_sourceHostName += "GHI"

# add string values to destination array
$global:P_destinationHostName = "zzz"
$global:P_destinationHostName += "yyy"

function test {
    Param(
        [string]$paramA="",
        [string]$paramB=""
    )

    Write-Host "test function > paramA: $paramA"
    Write-Host "test function > paramB: $paramB"
}

$i = 0
# Pass the individual value to a function
test ($Global:P_sourceHostName[$i],$Global:P_destinationHostName[$i])

#Pass the individual value to a function with an additional text
test ("AAA $Global:P_sourceHostName[$i]", "BBB $Global:P_destinationHostName[$i]")

What resulted is:

test function > paramA: ABC zzz
test function > paramB: 
test function > paramA: AAA ABC DEF GHI[0] BBB zzz yyy[0]
test function > paramB:

Question:

  1. Why the first call of test function, it resulted with a blank "paramB"?
  2. Why the second call of test function, it combines the text but does not resulted in the correct array value?

1 Answer 1

1
  1. Why the first call of test function, it resulted with a blank "paramB"?

Because the array is passed as a single argument to paramA. You need to use splatting to have the elements of an array passed to individual parameters.

$params = $global:P_sourceHostName[$i], $global:P_destinationHostName[$i]
test @params

Otherwise use distinct arguments (pass the parameters without a comma between them):

test $global:P_sourceHostName[$i] $global:P_destinationHostName[$i]

or named parameters:

test -paramA $global:P_sourceHostName[$i] -paramB $global:P_destinationHostName[$i]
  1. Why the second call of test function, it combines the text but does not resulted in the correct array value?

Because you put your variables in a string and PowerShell does only simple variable expansion inside strings. More complex things like index operators or dot-access are ignored. An expression like this

$a = 'a', 'b', 'c'
"$a[0]"

effectively becomes

$a = 'a', 'b', 'c'
($a -join ' ') + '[0]'

hence the output is

a b c[0]
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.