4

Is there a function, method, or language construction allowing to retrieve a single column from a multi-dimensional array in Powershell?

$my_array = @()
$my_array += ,@(1,2,3)
$my_array += ,@(4,5,6)
$my_array += ,@(7,8,9)

# I currently use that, and I want to find a better way:
foreach ($line in $my_array) {
    [array]$single_column += $line[1]    # fetch column 1
}
# now $single_column contains only 2 and 5 and 8

My final goal is to find non-duplicated values from one column.

3 Answers 3

5

Sorry, I don't think anything like that exist. I would go with:

@($my_array | foreach { $_[1] })

To quickly find unique values I tend to use hashtables keys hack:

$UniqueArray = @($my_array | foreach -Begin { 
    $unique = @{} 
} -Process { 
    $unique.($_[1]) = $null
} -End { 
    $unique.Keys 
})

Obviously it has it limitations...

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ! I just found the same solution before seeing you submitted it. For the second part... well... I try to find a better one :)
There are always few ways to skin a cat in PowerShell. :)
2

To extract one column:

$single_column = $my_array | foreach { $_[1] }

To extract any columns:

$some_columns = $my_array | foreach { ,@($_[2],$_[1]) }   # any order

To find non-duplicated values from one column:

$unique_array = $my_array | foreach {$_[1]} | sort-object -unique
# caveat: the resulting array is sorted,
# so BartekB have a better solution if sort is a problem

Comments

1

I tried @BartekB's solution and it worked for me. But for the unique part I did the following.

@($my_array | foreach { $_[1] } | select -Unique)

I am not very familiar with powershell but I am posting this hoping it helps others since it worked for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.