Union of array variables in powershell

Nandan Hegde 30,246 Reputation points MVP

I have 2 variables in my powershell script which are being provided values at run time via REST API outputs.

I take a union of both the variables to get the overall count as below

$a+ $b
and then take the count.
This works fine when $a has more than 2 values provided . In case of a single value it takes it as string and we get string concatenation and overall count becomes 1 even if $b has multiple elements.

How to handle the scenario in powershell while taking the union of array variables that 1st variable always be an array rather than string

@Rich Matheisen

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,435 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 100.8K Reputation points MVP

    Hi @Nandan Hegde ,

    you could just add the [array] in front of the variable name.

    Maybe this helps:

    [array]$a = "test1"  
    [array]$b = "test3","test4"  
    ($a + $b).Count  


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Andreas Baumgarten

    0 comments No comments

0 additional answers

Sort by: Most helpful