Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array returns the first element char instead of the whole element

I defined an Array:

function GetNames
{
    $names = New-Object System.Collections.ArrayList
    $names += "Drin"
    $names
}

Now I want to take the first name from the Array:

$names = GetNames
$firstName = $names[0]

So now $firstName instead of receive Drin I got D

like image 739
user979033 Avatar asked Dec 04 '25 11:12

user979033


1 Answers

If you retrieve the type of $names using GetType() you will see that $names is actually a string - thus you get the first character if you are accessing the first index:

IsPublic IsSerial Name                                     BaseType 
-------- -------- ----                                     --------
True     True     String                                   System.Object

Note: This is because you only have a single element in the pipeline. To force $names to be an array, you have to explicitly declare it:

$names = @(GetNames)

Also note that you don't have to use New-Object to create an array. You can also declare it using:

function GetNames
{
    @('Drin')
}
like image 150
Martin Brandl Avatar answered Dec 07 '25 00:12

Martin Brandl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!