读取CSV第1行的列并将其保存到变量

时间:2018-10-29 13:01:58

标签: powershell csv

我想从csv或其他txt文件中读取数据。数据应仅从第1行读取,第1行仅读取几列,然后将其保存到变量中,保存后删除该行。现在,我已经做到了:

Get-ChildItem -Path C:\path | ForEach-Object -Process {
$YourContent = Get-Content -Path $_.FullName
$YourVariable = $YourContent | Select-Object -First 1
$YourContent | Select-Object -Skip 1 | Set-Content -Path $_.FullName

我的问题是我的变量像这样打印出来:

Elvis;867.5390;elvis@geocities.com

所以我想将每个变量保存到自己的列中。 csv看起来像的例子:

Elvis | 867.5309     | Elvis@Geocities.com
Sammy | 555.1234     | SamSosa@Hotmail.com

3 个答案:

答案 0 :(得分:2)

使用Import-Csv代替Get-Content

Import-Csv file.csv -Delimiter ";" -Header A, B, C

答案 1 :(得分:1)

这是我想做的一种方法。

  1. 第8行制作一个要使用的文件。 [咧嘴]
  2. 第10行读取该文件
  3. 第11-13行将第一行转换为对象并删除不需要的属性
  4. 第14-15行抓取所有但第一行并发送以覆盖源文件
  5. 其余几行显示了[咧嘴]

代码:

$FileName = "$env:TEMP\Pimeydentimo.txt"

# create a file to work with
@'
Alfa;123.456;Some unwanted info;Alfa@example.com
Bravo;234.567;More info that can be dropped;Bravo@example.com
Charlie;345.678;This is also ignoreable;Charlie@example.com
'@ | Set-Content -LiteralPath $FileName

$InStuff = Get-Content -LiteralPath $FileName
$TempObject = $InStuff[0] |
    ConvertFrom-Csv -Delimiter ';' -Header 'Name', 'Number', 'DropThisOne', 'Email' |
    Select-Object -Property * -ExcludeProperty DropThisOne
$InStuff[1..$InStuff.GetUpperBound(0)] |
    Set-Content -LiteralPath $FileName    

$InStuff
'=' * 30
$TempObject
'=' * 30
Get-Content -LiteralPath $FileName

输出...

Alfa;123.456;Some unwanted info;Alfa@example.com
Bravo;234.567;More info that can be dropped;Bravo@example.com
Charlie;345.678;This is also ignoreable;Charlie@example.com
==============================

Name Number  Email           
---- ------  -----           
Alfa 123.456 Alfa@example.com
==============================
Bravo;234.567;More info that can be dropped;Bravo@example.com
Charlie;345.678;This is also ignoreable;Charlie@example.com

答案 2 :(得分:0)

感谢您的回答!

我尝试澄清更多我想做的事情。答案可能已经做到了,但是我对Powershell的了解还不够好,仍然学到了很多东西。

如果我有csv或任何其他txt文件,我想读取文件的第一行。该行包含多个信息。我还希望将每条信息都保存到变量中。将信息保存到变量后,我想删除该行。

示例:

汽车模型年

福特嘉年华2015

奥迪A6 2018

在此示例中,我想将Ford,Fiesta和2015保存到变量(第1行)($ Card,$ Model,$ Year)中,然后将其删除。第二行不应该删除,因为稍后会用到