【问题标题】:Get all columns in a row from Import-CSV with other delimiter使用其他分隔符从 Import-CSV 获取一行中的所有列
【发布时间】:2017-05-28 02:10:24
【问题描述】:

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

【问题讨论】:

  • Import-CsvExport-CSV-Delimiter 参数,您可以使用管道字符而不是 -join

标签: powershell csv import-csv


【解决方案1】:

我认为您正在寻找 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

所以你会插入一个选择对象:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 2018-01-19
    • 2014-08-14
    • 2016-03-13
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多