Test User
Test User

Reputation: 47

Call Powershell Import-Csv cmdlet with variable -Header

The total number and position of fields vary from file to file, but the fields in which I am interested are always present. File1.csv looks like this:

1,1.0,one
2,2.0,two

See code below:

function Read_Headers_From_File($filename)
{
    # Yes, I am not reading a file right now
    "int,float,string"
}

$header1 = Read_Headers_From_File("file1.ini")
$file1 = Import-Csv -Header $header1 file1.csv
# $header2 = Read_Headers_From_File("file2.ini")
# $file2 = Import-Csv -Header $header2 file2.csv
echo $file1

The output is:

int,float,string
----------------
1
2

The "int,float,string" is interpreted as a single field named "int,float,string". Is there a way to make -Header "field1,field2,field3" work like -Header field1,field2,field3?

Upvotes: 1

Views: 2483

Answers (2)

Test User
Test User

Reputation: 47

I edited the question radically. What I want can be achieved by this:

$header1 = Read_Headers_From_File("file1.ini")
$file1 = Invoke-Expression ("Import-Csv " + "-Header " + $header1 + " file1.csv")

This also works:

# The ini file has a single row
# field1,field2,field3,...
function Read_Headers_From_File($ini_file)
{   
    $temp = Get-Content $ini_file
    # return array of args for -Header 
    $temp.Split(",")
}

$header1 = Read_Headers_From_File("file1.ini")
$file1 = Import-Csv file1.csv -Header $header1
echo $file1

Sorry for the noise. If possible please delete the question.

Upvotes: 0

Χpẘ
Χpẘ

Reputation: 3451

You can do this to exclude a column, say y:

$userdata = Import-Csv test.csv | select-object * -exclude y

Although you didn't ask you can do this to rename columns:

# Assume you want to use the header names x,y,z instead of what 
# is specified in the header line of the file
# The Header parameter allows you to specify headers for a CSV that (nominally)
# doesn't contain a header line. But if the CSV file does contain a header line
# and -Header is specified then the header line is treated like a data line.
# The select -skip 1 discards the header-line-as-data row

$userdata = Import-Csv -Header x,y,z test.csv | select-object -skip 1

Upvotes: 2

Related Questions