ConvertTo-Csv Output without quotes

前端 未结 14 963
慢半拍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 09:02

    This is pretty similar to the accepted answer but it helps to prevent unwanted removal of "real" quotes.

    $delimiter = ','
    Get-Process | ConvertTo-Csv -Delimiter $delimiter -NoTypeInformation | foreach { $_ -replace '^"','' -replace "`"$delimiter`"",$delimiter -replace '"$','' }
    

    This will do the following:

    • Remove quotes that begin a line
    • Remove quotes that end a line
    • Replace quotes that wrap a delimiter with the delimiter alone.

    Therefore, the only way this would go wrong is if one of the values actually contained not only quotes, but specifically a quote-delimiter-quote sequence, which hopefully should be pretty uncommon.

    0 讨论(0)
  • 2020-12-01 09:02

    I wrote this for my needs:

    function ConvertTo-Delimited {
    
        [CmdletBinding()]
        param(
            [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
            [psobject[]]$InputObject,
            [string]$Delimiter='|',
            [switch]$ExcludeHeader
        )
        Begin {
    
            if ( $ExcludeHeader -eq $false ) {
                @(
                    $InputObject[0].PsObject.Properties | `
                    Select-Object -ExpandProperty Name
                ) -Join $Delimiter          
            }
    
        }
        Process {
    
            foreach ($item in $InputObject) {
                @(
                    $item.PsObject.Properties | `
                    Select-Object Value | `
                    ForEach-Object { 
                        if ( $null -ne $_.Value ) {$_.Value.ToString()} 
                        else {''} 
                    }
                ) -Join $Delimiter
            }
    
        }
        End {}
    
    }
    

    Usage:

    $Data = @(
        [PSCustomObject]@{
            A = $null
            B = Get-Date
            C = $null
        }
        [PSCustomObject]@{
            A = 1
            B = Get-Date
            C = 'Lorem'
        }
        [PSCustomObject]@{
            A = 2
            B = Get-Date
            C = 'Ipsum'
        }
        [PSCustomObject]@{
            A = 3
            B = $null
            C = 'Lorem Ipsum'
        }
    )
    
    # with headers
    PS> ConvertTo-Delimited $Data
    A|B|C
    1|7/17/19 9:07:23 PM|Lorem
    2|7/17/19 9:07:23 PM|Ipsum
    ||
    
    # without headers
    PS> ConvertTo-Delimited $Data -ExcludeHeader
    1|7/17/19 9:08:19 PM|Lorem
    2|7/17/19 9:08:19 PM|Ipsum
    ||
    
    0 讨论(0)
提交回复
热议问题