none
[PowerShell] Pass array value to a function RRS feed

  • Question

  • I'm new to Powershell (Newbie Alert!!)

    I have created the following to get <g class="gr_ gr_14 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" data-gr-id="14" id="14">understanding</g> 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 <g class="gr_ gr_7 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" data-gr-id="7" id="7">resulted</g> in the correct array value?


    • Edited by te_ve Tuesday, October 24, 2017 2:00 AM remove the html
    • Moved by Bill_Stewart Thursday, January 25, 2018 9:53 PM Abandoned/unreadable
    Tuesday, October 24, 2017 1:58 AM

All replies

  • In PowerShell arguments are NOT separated by commas.

    Here is the correct way to write this.

    function test {
    	param(
    		[string]$paramA,
    		[string]$paramB
    	)
    	write-host "test function > paramA: $paramA"
    	write-host "test function > paramB: $paramB"
    }
    
    $P_sourceHostName = "ABC", "DEF", "GHI"
    $P_destinationHostName = "zzz", "yyy"
    
    $i = 1
    #Pass the individual value to a function
    test $P_sourceHostName[$i] $P_destinationHostName[$i]
    
    #Pass the individual value to a function with an additional text
    test "AAA $($P_sourceHostName[$i])" "BBB $($P_destinationHostName[$i])"


    \_(ツ)_/

    Tuesday, October 24, 2017 5:57 AM