2

I have an array where each element is a hashtable. Each hashtable has the same keys. Here it is:

@(
    @{"MarketShortCode"="abc";"MarketName"="Market1"    },
    @{"MarketShortCode"="def";"MarketName"="Market2"    },
    @{"MarketShortCode"="ghi";"MarketName"="Market3"    },
    @{"MarketShortCode"="jkl";"MarketName"="Market4"    }
)

I want a nice elegant way to extract an array containing just the value of the MarketShortCode key. So I want this:

@("abc","def","ghi","jkl")

This is the best I've come up with:

$arr = @()
$hash | %{$arr += $_.MarketShortCode}
$arr

But I don't like that cos its three lines of code. Feels like something I should be able to do in one line of code. Is there a way?

1 Answer 1

2

Just do this:

$hash | %{$_.MarketShortCode}

That is, return the value from the block instead of adding it to an array and then dereferencing the array.

If you're using PowerShell 3+, there's even shorter way:

$hash.MarketShortCode

PowerShell automatically applies dot . to each item in an array when it's used this way, but it wasn't supported until v3.

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

3 Comments

easy as that eh!! Thanks @briantist. Apparently I have to wait 9 minutes before I can mark that as an answer.
(This is fairly subjective but) I really prefer $hash | %{$_['MarketShortCode']} over the "property"-type deference ($_.MarketShortCode) - the latter is ambiguous, ["key"] isn't
@MathiasR.Jessen I prefer dot notation when the property name is to be hard-coded in the script, and item notation (probably not the correct term) with brackets when the name will be generated or chosen at runtime.

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.