Hsing Yi
Hsing Yi

Reputation: 173

How to get one of split item in csv record in powershell?

I have the following csv file which contains an address field which needs to be extracted:

"date","location","field1"  
"2017/01/01 10:32","44 Shirley St. West Chicago, IL 60185","1"  
"2017/01/02 07:06","70 Bowman St. South Windsor, CT 06074","1" 

Here is my script:

$input = $ARGS[0]

$lines = import-csv $input | select location
foreach ($l in $lines) {
    $a= $l -split 'St\.'
    $a[0]
}

I just need the street information, but it shows the following:

@{location=44 Shirley   
@{location=70 Bowman 

How can I fix it?

Upvotes: 1

Views: 50

Answers (2)

Mark Wragg
Mark Wragg

Reputation: 23355

Per the comments, this is not going to work for every address (as they don't all end street) but assuming in your file they do and you just want the name of the street without the 'St.' part per your split, the only issue with your code is with the Select statement.

To fix you need to use the -ExpandProperty parameter so that you get the value of the Location property returned, rather than a filtered object with only that property:

$lines = import-csv $input | select -ExpandProperty Location
foreach ($l in $lines) {
    $a= $l -split 'St\.'
    $a[0]
}

Returns:

44 Shirley 
70 Bowman

Upvotes: 1

user6811411
user6811411

Reputation:

An alternative to Marks solution:

$lines = import-csv $input 
foreach ($l in $lines) {
    $a= $l.location -split 'St\.'
    $a[0]
}

Upvotes: 1

Related Questions