Powershell中的CSV数据库文件分割器

时间:2017-10-13 20:18:55

标签: powershell csv

我有一个导出为CSV文件的数据库文件

  

[表格]
  "地址"
  [场]
  " StreetNum"" StreetName"" AptNum""市""国""邮编: #34;
  [DATA]
  6445,' High Land Rd',623,' Bloomington' IL',12345
  [表格]
  " VersionTable"
  [场]
  "表名"" MajVersion"" MINVERSION""用户ID""已更新""版本& #34;
  [DATA]
  ' Macro',1,0,-1,' 2009/10/24 10:23:17',0
  '个人',1,0,-1,' 2015/10/24 10:23:17',0
  ' ProfileAccounts',1,0,0,' 2016/10/26 11:22:21',2
  [表格]
  "名称"
  [场]
  "姓""名字"" MidName"
  [DATA]
  '地理位置''琼斯'' L'
  '狮子座''大卫'''
  '新''斯塔福德'' K'

我需要将其拆分为文件名作为表名

Address.CSV

  

" StreetNum"" StreetName"" AptNum""市""状态"&# 34;邮编及#34;
  6445,' High Land Rd',623,' Bloomington' IL',12345

VersionTable.CSV

  

"表名"" MajVersion"" MINVERSION""用户ID""已更新"&# 34;版本"
  ' Macro',1,0,-1,' 2009/10/24 10:23:17',0
  '个人',1,0,-1,' 2015/10/24 10:23:17',0
  ' ProfileAccounts',1,0,0,' 2016/10/26 11:22:21',2

Name.CSV

  

"姓""名字"" MidName"
  '地理位置''琼斯'' L'
  '狮子座''大卫'''
  '新''斯塔福德'' K'

1 个答案:

答案 0 :(得分:0)

$file = Get-Content D:\test\originalFile.txt #file from question
foreach ($line in $file)
{
    #lines with description only start section and are omitted
    If ($line -eq "[TABLE]") { 
        $section = "file_name"
        continue
    }
    If ($line -eq "[FIELDS]") {
        $section = "field_names"
        continue
    }
    If ($line -eq "[DATA]") {
        $section = "data_in_fields"
        continue
    }

    if ($section -eq "file_name") { #one line with file name
        $filename = $line.Substring(1,$line.Length-2) + ".csv"
        Write-Host "filename :"$filename
    }
    if ($section -eq "field_names") { #one line with column names
        $fields = $line
        $fields | Set-Content $PSScriptRoot\$filename 
        Write-Host "fields :"$fields
    }   
    if ($section -eq "data_in_fields") { #multiple lines with data
        $data = $line
        $data | Add-Content $PSScriptRoot\$filename
        Write-Host "data :"$data
    }

 }
 Read-Host -Prompt "Press Enter to exit"