1

我有一个包含 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()
4

1 回答 1

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 {
于 2017-01-12T20:53:17.833 回答