使用其他分隔符

时间:2017-01-12 20:14:56

标签: powershell csv import-csv

我有一个包含100多列的CSV。有时当我运行脚本时,我想选择几列,但有时我需要所有列。它将被写入|管道分隔文件。

是否有Import-CSV的命令/属性可以在不指定所有标题的情况下获得完整行?

我尝试了下面的代码,但我有一个挂|当我想要所有列时,在行上管道。

# powershell -ExecutionPolicy ByPass -File .\test.ps1 -NoExit -AllColumns
param(
    [switch]$AllColumns = $false
)
$writer = New-Object IO.StreamWriter('output.txt')
Import-Csv 'test.csv' | ForEach-Object {
    $writeLine = ""

    if($_.("Name") -eq "John") {
        if($AllColumns) {

            #$writeLine = All Columns with '|' delimiter     
            foreach ($property in $_.PSObject.Properties) {
                $writeLine = ($writeLine + $property.Value + '|')
                # Or this - $writeLine = ($writeLine, $property.Value -join '|')
            }

        } else {
            $writeLine = ($_.("Name"), $_.("Code") -join '|')
        }
    }
    $writer.WriteLine($writeLine)
}

$writer.Close()

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找Select-Object cmdlet。示例功能

Import-Csv -Path 'C:\2Users50columns.csv' `
| Select-Object -Property 'Name','Classification','Age'

Name           : Esuriency  
Classification : Member
Age            : 35 minutes ago

Name           : Shawn
Classification : Member
Age            : 27

所以你要插入一个Select-Object:

Import-Csv -Path 'text.csv' | Select-Object ... | Foreach-Object {