簡體   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