1

I'm trying to pass a range as an array so I can return an array in PowerShell:

function iterHostsToArray($arr, $str) {
   $hostz = @()
   $arr | % { $hostz = "$($str)$($_)" }
   return $hostz
}

$skybarHosts = iterHostsToArray((1..2), 'BAR')
$skyboxHosts = iterHostsToArray((1..6), 'BOX')

And I'm expecting the following:

PS> $skybarHosts
BAR1
BAR2

PS> $skyboxHosts
BOX1
BOX2
BOX3
BOX4
BOX5
BOX6

I'm refactoring from something like this, which works:

$skybarHosts = @()
(1..2) | % { $skybarHosts += "HCPNSKYBAR$($_)" }
1
  • 1
    You are overwriting the $hostz variable in each iteration. also, when a function should return an array, preceed that with a comma. This unary comma ensures the returned value is an array, even if it has just one element. Commented Jan 14, 2021 at 20:10

1 Answer 1

3

There are two issues. The first is a common pitfall in Powershell: function definitions use commas to separate parameters, but function calls use spaces. The syntax to pass a range and string is like so,

iterHostsToArray (1..2) 'BAR'

Another an issue is that the $hostz array is overwritten, not appended. Use += to append new elements into the array like so,

$hostz = @()
$arr | % { $hostz += "$($str)$($_)" }

As mentioned in comment, if all the function does is creation of an array, it can be simplified a bit. When the $arr is passed to a foreach iterator and no assignment is done, the output is passed along the pipeline and the function returns an array of objects. Like so,

function iterHostsToArray($arr, $str) {
    $arr | % {  "$($str)$($_)" }         
}

This approach, of course, doesn't work if you'd like to do work with the array contents within the function. In that case,

function iterHostsToArray($arr, $str) {
    $hostz = $arr | % {  "$($str)$($_)" }
    # Do sutff with $hostz
    # ...

    # finally, either
    return $hostz    
    # or simply
    $hostz 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Actually there is no need for the $hostz variable as PowerShell builds up the output array automatically, very efficiently: function iterHostsToArray($arr, $str) { $arr | % { "$str$_" } }.

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.