Search code examples
powershellvariablesconcatenationinputboxarrayobject

Extract data string from an array and assign them to a variable by concatenation in PowerShell


I have an array of objects like:

$arrayServ = New-Object System.Collections.ArrayList(,$serv)

this array contains some objects like:

name        prefix                     tenants                  
----        ------                     -------                  
TOTO        http://home/toto           bob, michael, ramy, anna
Nav         http://8.8.8.8/google      com, uk, fr

I'm trying to Extract all data in the property name and put them in a variable and concatenate this variable with another variable which is a counter of the name.

Something like this:

$liste = "$i. $arrayServ [$i]"

Why I want do that ? It's because, I want to display that $liste in an InputBox, like:

$liste = "$i. $arrayServ [$i]"
$msg = $liste -join "`n"
$item = InputBox $msg -title "Your choice"

The InputBox "Your choice"

enter image description here

Does someone know how can I do that please ?


Solution

  • As far as I can tell, you already have an array of objects in $serv, so there should be no reason to put this in an ArrayList..

    If that is the case, you could create the $liste array like this:

    $liste = @()
    $i = 1
    $serv | Select-Object -ExpandProperty name | ForEach-Object {
        $liste += "{0}. {1}" -f $i++, $_
    }
    

    and then use it for the inputbox message using

    $msg = $liste -join [Environment]::NewLine
    

    Using your examples, this would return

    1. TOTO
    2. Nav
    

    Putting this in an inputbox:

    Add-Type -AssemblyName 'Microsoft.VisualBasic'
    $item = [Microsoft.VisualBasic.Interaction]::InputBox($msg, "Votre choix")
    

    enter image description here