Chris White
Chris White

Reputation: 71

Get name value of a powershell object property into a string

I have imported a csv file

$infile = import-csv .\myfile.csv

Now I can show the columns (now object properties) by

$infile | gm -type NoteProperty

Name      MemberType

-------   ----------

Column1   NoteProperty

Column2   NoteProperty

etc...

What I want to do is get the value of the Name(Column1..) into a variable.

Upvotes: 1

Views: 7814

Answers (4)

user3569698
user3569698

Reputation:

When importing cdv files using powershell, I normally specify a delimiter incase of more than a single value. Hope this helps all.

Example csv file

 Key     ValueA     ValueB
 ref1    valueA1    valueB1
 ref2    valueA2    valueB2

When opening a csv file using notepad

 Key;ValueA;ValueB
 ref1;valueA1;valueB1
 ref2;valueA2;valueB2

Using powershell to import that csv file into a variable

 $Hash = Import-Csv -path d:\test.csv -Delimiter ';'

Using powershell to query the csv file

 $Hash = Import-Csv -path d:\test.csv -Delimiter ';' |? {$_.ValueA -eq 'x' -and $_.ValueB -eq 'y'} | Select -exp Key

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200473

Another way would be to go through PSObject:

$infile[0].PSObject.Properties |
  ? { $_.MemberType -eq 'NoteProperty' } |
  select -Expand Name

Using $infile[0] selects the first object from the collection, otherwise .PSObject.Properties would return the properties of the collection instead of the properties of a collection element.

Upvotes: 2

Sam Porch
Sam Porch

Reputation: 771

You can use select

$infile | gm -type NoteProperty | select -ExpandProperty Name

e.g.,

$Names = @( $infile | gm -type NoteProperty | select -ExpandProperty Name )

Upvotes: 7

djs
djs

Reputation: 1700

This should print Column1:

$infile = import-csv .\myfile.csv
$gm = $infile | gm -type NoteProperty
$name = $gm[0].Name
$name

Upvotes: 0

Related Questions