繁体   English   中英

如何使用PowerShell导入CSV并从文本文件中读取一行?

[英]How to Import a CSV and read a line from text file using PowerShell?

我有一些PowerShell Cmdlet的输出,如下所示

  0    server-1 Content  Damaged       client 12/06/2013 08:00:41
123    server-1 Content  Damaged       client 12/07/2013 08:00:33
  0    server-1 Content  Damaged       client 12/08/2013 08:00:32
234    server-1 Content  Damaged       client 12/09/2013 08:00:34
  0    server-1 Content  Damaged       client 12/09/2013 16:09:41
 70    server-1 Content  Damaged       client 12/10/2013 08:00:33
  0    server-1 Content  Damaged       client 12/11/2013 08:00:31

我可以将上面的输出附加到文本文件中。

当我尝试在新的CSV文件中导入以上输出时(使用Import-Csv ),所有信息都在每行的单个单元格下,但我需要每行7个单元! 请有人在这里指导我。

还请告诉我,如何使用PowerShell从0开始的线路?

默认情况下, Import-CSV假定每个记录(或行)数据都以逗号分隔(因此名称以逗号分隔的值)。 如果您有其他一些用作字段之间的分隔符(例如制表符或空格)的其他内容,则可以使用cmdlet的-Delimiter参数指定该-Delimiter并使其正确解析。

但是, Import-CSV还假定您有一个标题记录,而您没有。 因此,您需要使用Get-Content来解析数据,或者添加标头记录(最好)。

一旦将数据解析为对象集合(或实际上是集合集合),只需查看每个对象的第一个值,看它是否等于0。

数据不是CSV格式,因此Import-CSV无效。 您需要将每一行拆分为单独的值,并使用这些值创建PS对象。 每个值都需要分配给对象的属性,因此您还需要为每个值分配属性名称。

在Powershell中有很多方法可以实现这一目标。 这是一个。 属性名称只是Prop1-Prop7。 您需要用有意义的东西替换那些,并用您的文件规范替​​换testfile.txt文件名。

#Create an array of property names
$Props = &{$args} Prop1 Prop2 Prop3 Prop4 Prop5 Prop6 Prop7

Get-Content testfile.txt |
 ForEach-Object {
    $Parts = $_ -split '\s+'  #Split the line at the spaces to create an array of values
    $PropHash = [ordered]@{}  #Create an empty hash table for the property hash (the [ordered] is optional, but keeps the properties in the same order as the property list)
    for ($i=0; $i -le 6; $i++) 
     {$PropHash[$Props[$i]] = $Parts[$i]} #Assign the split values to the property names by their respective array indexes
    [PSCustomObject]$PropHash #Output a PSCustomObject built from the hash table
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM