leeand00
leeand00

Reputation: 26422

Powershell pass a range as an array?

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$($_)" }

Upvotes: 1

Views: 111

Answers (1)

vonPryz
vonPryz

Reputation: 24091

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 
}

Upvotes: 3

Related Questions