ChrisB
ChrisB

Reputation: 37

In PowerShell, how can I extract a key-value pair from an array of records?

I am reading data from a CSV file and want to extract the URL value (abc.com, def.com). My simple code returns the data in an array of key-value pairs (see below), but I haven't been able to extract an individual item.

@{Product=a; Description=xyz; URL=abc.com}

@{Product=b; Description=abc; URL=def.com}

I tried indexing into the array, using IndexOf, etc. Any suggestions?

    $list = Import-Csv ".\file"

    foreach ($item in $list) {

        write-host $item
    }

Upvotes: 0

Views: 3214

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174495

Those are not arrays of key-value pairs, but custom objects created from the rows of your CSV.

You can either use PowerShell's property enumeration behavior to grab all values from the URL property of each object:

$allURLs = $list.URL

Or use ForEach-Object -MemberName to grab only a single property value from a collection:

$allURLs = $list |ForEach-Object -MemberName URL

If you need this to run in PowerShell earlier than version 3.0, use Select-Object -ExpandProperty:

$allURLs = $list |Select-Object -ExpandProperty URL

Upvotes: 2

Related Questions