有没有办法强制PowerShell -Export-CSV cmdlet维护特定的列顺序?

led*_*per 12 csv powershell

我是powershell的新手,因此脚本是来自网站的各种示例的弗兰肯斯坦.

我的问题是如何确保我为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...
Run Code Online (Sandbox Code Playgroud)

我希望文件按照我在脚本中指定的顺序排列,但是当我在记事本或excel中打开它时,列会以看似随机的顺序出现.关键词似乎因为他们可能有一些自我排序的方法.

Jas*_*irk 18

在PowerShell V3中,而不是:

        $csv+=New-Object PSObject -Property @{
Run Code Online (Sandbox Code Playgroud)

我会用:

        $csv+=[pscustomobject]@{
Run Code Online (Sandbox Code Playgroud)

将哈希文字转换为[ordered]或[pscustomobject] 时,PowerShell V3解析器将保留键的顺序.这种方法的一个小方面好处 - 它也会更快.

如果您使用的是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 |
    ...
Run Code Online (Sandbox Code Playgroud)


alr*_*roc 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
Run Code Online (Sandbox Code Playgroud)

但是,您可以稍微短路一下.根据$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
Run Code Online (Sandbox Code Playgroud)