aditya pratti
aditya pratti

Reputation: 35

Extract Each object from a CSV file using powershell

I am new to Powershell.I have a csv file named samplemap.csv with values . I have to read each value from the file, like example a variable to define the value of paris_App.

CntryApp Version
paris_App 2.19
ila_App 5.3
sga_App 3.10

The code I used is printing all the CntryApp version , not printing each CntryApp version separately

Import-CSV "H:\samplemap.csv"
$CntryApp = @()
$Version = @()
 Import-CSV "H:\samplemap.csv" -Delimiter ';'
ForEach-Object {
        $CntryApp += $_.CntryApp
        $Version += $_.Version
}

Expected 2.19,5.3,3.10 to be assigned to a indivdual variable . I mean each CntryApp version to be assigned to a variable.

Upvotes: 0

Views: 329

Answers (2)

Robert Dyjas
Robert Dyjas

Reputation: 5217

To import data from .csv file (space-delimited in that case) you have to specify delimiter (unless it matches the default one which might be dependent on your regional settings and I'm pretty sure that space is not the default one).

If you want to use that data later, it's good to save the imported values to variable:

$t = Import-CSV "$($pwd.path)\samplemap.csv" -Delimiter ' '

Once you save it, you can access it using the following structure

# All values of CntryApp
$t.CntryApp

# Output
paris_App
ila_App
sga_App

# CntryApp and version of first object
$t[0]

# Output
CntryApp  Version
--------  -------
paris_App 2.19

# Version of first app
$t[0].Version

# Output 
2.19

As you mentioned key:value scenario, it'd be natural (although it might look a bit more complex) to consider hastable as @Matt suggested.

Upvotes: 0

Matt
Matt

Reputation: 46680

If I understand you correctly you want individual variables for each entry in your input file e.g. $paris_App? While that is possible using something like Set-Variable a better approach would be creating a hashtable of those key value pairs. That was you could call the version if you know the name.

$apps = @{}
Import-CSV "H:\samplemap.csv" -Delimiter ';' | ForEach-Object{
    $apps[$_.CntryApp] = $_.Version
}

$apps['sga_app']

This approach would fail if those CntryApp contained duplicates.

Upvotes: 1

Related Questions