使用变量-Header调用Powershell Import-Csv cmdlet

时间:2016-03-11 23:10:16

标签: csv powershell

字段的总数和位置因文件而异,但我感兴趣的字段始终存在。 File1.csv如下所示:

  

1,1.0,一个
  2,2.0,2

请参阅以下代码:

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

输出结果为:

  

整数,浮点,字符串
  ----------------
  1
  2
  

  " int,float,string"被解释为名为" int,float,string"的单个字段。有没有办法让-Header" field1,field2,field3"像-Header field1,field2,field3?

那样工作

2 个答案:

答案 0 :(得分:0)

您可以这样做以排除列,例如y:

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

虽然你没有要求你可以这样做来重命名列:

# 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

答案 1 :(得分:0)

我从根本上编辑了这个问题。我想要的就是这个:

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

这也有效:

# 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

对不起噪音。如果可能请删除问题。