ConvertTo-Csv Output without quotes

前端 未结 14 979
慢半拍i
慢半拍i 2020-12-01 08:03

I am using ConvertTo-Csv to get comma separated output

 get-process | convertto-csv -NoTypeInformation -Delimiter \",\"

It out

14条回答
  •  温柔的废话
    2020-12-01 08:54

    This function takes a powershell csv object from the pipeline and outputs like convertto-csv but without adding quotes (unless needed).

    function convertto-unquotedcsv {
        param([Parameter(ValueFromPipeline=$true)]$csv, $delimiter=',', [switch]$noheader=$false)
        begin {
          $NeedQuotesRex = "($([regex]::escape($delimiter))|[\n\r\t])"
          if ($noheader) { $names = @($true) } else { $names = @($false) }
        } 
        process {
          $psop = $_.psobject.properties
          if (-not $names) {
            $names = $psop.name | % {if ($_ -match $NeedQuotesRex) {'"' + $_ + '"'} else {$_}}
            $names -join $delimiter   # unquoted csv header
          }
          $values = $psop.value | % {if ($_ -match $NeedQuotesRex) {'"' + $_ + '"'} else {$_}}
          $values -join $delimiter    # unquoted csv line
        } 
        end {
        }
    }
    

    $names gets an array of noteproperty names and $values gets an array of notepropery values. It took that special step to output the header. The process block gets the csv object one piece at a time.

    Here is a test run

    $delimiter = ','; $csvData = @"
    id,string,notes,"points per 1,000",number
    4,"a delimiter$delimiter is in here,","test data 3",1,348
    5,"a comma, is in here,","test data 4`r`nwith a newline",0.5,347
    6,hello world2.,classic,"3,000",123
    "@
    
    $csvdata | convertfrom-csv | sort number | convertto-unquotedcsv -delimiter $delimiter
    
    id,string,notes,"points per 1,000",number
    6,hello world2.,classic,"3,000",123
    5,"a comma, is in here,","test data 4
    with a newline",0.5,347
    4,"a delimiter, is in here,",test data 3,1,348
    

提交回复
热议问题