2013-09-25 102 views
11

我是powershell的新手,所以腳本是來自網站的各種示例的科學怪人。有沒有辦法強制powershell -Export-CSV cmdlet維護特定的列順序?

我的問題是如何確保我爲DataTable創建的csv文件保持我指定的列順序?

我的腳本,這樣做是爲了填充CSV標題和值,像這樣:

...snip... 
$dataTable | ForEach-Object { 
      $csv+=New-Object PSObject -Property @{ 
       program_code=$_.ProgramCode; 
       first_name=$_.FirstName; 
       last_name=$_.LastName; 
       email=$_.email; 
       phone=$_.phone; 
       phone2=$_.otherphone; 
       address=$_.addr1; 
       address2=$_.addr2; 
       city=$_.city; 
       state=$_.state; 
       postal_code=$_.Zip; 
       country=$_.Country; 
       grad_year=$_.HsGradDate; 
       lead_date=$_.LeadDate; 
       lead_source=$_.LeadSource; 
       school_status=$_.SchoolStatus; 
     } 
     } 
    $csv | Export-CSV C:\scripts\NewLeads$(Get-Date -Format yyyyMMdd).csv -notype -Append 
...snip... 

我想讓該文件必須列在我的腳本中指定,但是當我在記事本打開它的順序或excel列出現在一個看似隨機的順序。關鍵詞似乎是因爲他們可能有一些排序的方法。

回答

15

在PowerShell中V3,:

 $csv+=New-Object PSObject -Property @{ 

我會用:

 $csv+=[pscustomobject]@{ 

PowerShell的V3解析器將保留鍵的順序,當你施放一個哈希字面可以[ordered]或[pscustomobject]。這種方法有一點小好處 - 它也會更快。

如果您使用的是V2,則需要跳過-Property參數到New-Object,而是使用多次調用Add-Member。它看起來像這樣:

$csv+=New-Object PSObject | 
    Add-Member -Name program_code -Value $_.ProgramCode -MemberType NoteProperty -PassThru | 
    Add-Member -Name first_name -Value $_.FirstName -MemberType NoteProperty -PassThru | 
    ... 
+0

謝謝,這兩個很好的解決方案!你需要少一些打字,我是一個很大的粉絲。 – ledgeJumper

+0

使用[pscustomobject] @ {}表示法對v2方法非常有幫助,謝謝 – flux9998

10

按所需順序選擇字段,然後導出。

$csv | select-object -property program_code,first_name,last_name,email,phone,phone2,address,address2,city,state,psotal_code,country,grad_year,lead_date,lead_source,school_status | 
Export-CSV C:\scripts\NewLeads$(Get-Date -Format yyyyMMdd).csv -notype -Append 

但是,您可能可以短路這一點。根據$dataTable的實際情況,您可能(應該在大多數情況下)能夠直接從該對象中進行選擇,並繞過創建PSObjects的集合。但是,如果您需要自定義標題,則需要使用select-object中的表達式(換行符以提高可讀性)。

代替
$dataTable| select-object @{Name="program_code";Expression={$_.ProgramCode}},` 
@{Name="first_name";Expression={$_.firstname}},` 
@{Name="last_name";Expression={$_.lastname}},email,phone,` 
@{Name="phone2";Expression={$_.otherphone}},` 
@{Name="addr1";Expression={$_.address}},` 
@{Name="addr2";Expression={$_.address2}},city,state,` 
@{Name="postal_code";Expression={$_.zip}},country,` 
@{Name="grad_year";Expression={$_.hsgraddate}},` 
@{Name="lead_date";Expression={$_.leaddate}},` 
@{Name="lead_source";Expression={$_.leadsource}},` 
@{Name="school_status ";Expression={$_.schoolstatus }}| 
Export-CSV C:\scripts\NewLeads$(Get-Date -Format yyyyMMdd).csv -notype -Append 
相關問題