2013-09-25 55 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 
相关问题