Union of array variables in powershell

Nandan Hegde 29,896 Reputation points MVP
2022-11-07T06:59:50.727+00:00

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,390 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 97,731 Reputation points MVP
    2022-11-07T07:14:30.07+00:00

    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)

    Regards
    Andreas Baumgarten

    0 comments No comments

0 additional answers

Sort by: Most helpful