#powershell Auto Type Conversion – String Array Concatenation

$a1 = “apple”
$a2 = “pear”, “guava”

# add/join 2 string arrays together
[array]$fruits = $a1 + $a2
$fruits
# applepear guava
# $a1 is a simple string type;
# $a2 string array auto expanded and added to same string object

$fruits.count #1 unique string
$fruits.GetType() #a single unit of string array

# one correct way to add/join 2 string arrays together
# force conversion of $a1 simple string to a string array
$fruits = @($a1) + $a2
$fruits
<#
apple
pear
guava
#>

$fruits.count #3 items in array
$fruits.GetType() #an array of strings

$fruits[1]
# pear

#alternative if the order is not important
$fruits = $a2 + $a1
$fruits
<#
pear
guava
apple
#>

$fruits.GetType() #an array of 3 strings

Bookmark the permalink.

Leave a Reply