Search code examples
powershellimport-csv

Out-GridView is showing a blank column where there is actual data


I have this CSV file.

The actual CSV data is delimited with a ";" , like this:

[2017-04-27 15:45:04] ;x;/x;Succes;

You can see there is a column "Terminaison" which contains success or failure information. My goal is to display all columns of the file in a Gridview.

I'm doing :

import-csv "C:\x\Journal\Capsule\CapsulePoste.csv" -Delimiter ";"

and get the desired output with all columns containing the proper data:

Now here is my question: when I want to display all that in a GridView, the "terminaison" column is all empty? Why? All other columns are properly displayed... :

import-csv "C:\x\Journal\Capsule\CapsulePoste.csv" -Delimiter ";" | out-gridview

I've found that a blank space at the end of the header (first line of csv file) is causing this...

Date;Trousse;Version;Demandeur;Action;Paramètres;Terminaison 

(there is a blank space right there after "Terminaison")

If i edit the csv in Notepad and remove that blank space, bingo, it works. However that doesn't solve my problem as I don't want to edit the file before-hand. What is this strange limitation and is there a workaround?


EDIT:

Answers provided below are great. I ended up using another option which i find is worth adding to the possibilities :

$content = Get-Content C:\x\Journal\Capsule\CapsulePoste.csv 
$content | Foreach {$_.TrimEnd()} | Set-Content C:\x\Journal\Capsule\CapsulePoste.csv
import-csv "C:\x\Journal\Capsule\CapsulePoste.csv" -Delimiter ";"| sort-object Date -descending

Solution

  • Here's a generic way to fix it after you've imported the CSV:

    $CSV = import-csv "C:\x\Capsule\CapsulePoste.csv" -Delimiter ";"
    
    $FixedObject = $CSV | ForEach-Object {
        $NewObject = New-Object -TypeName PSCustomObject
        $_.PSObject.Properties | ForEach-Object { $NewObject | Add-Member -Name $_.Name.Trim() -Value $_.Value -MemberType $_.MemberType }
    
        $NewObject
    }
    
    $FixedObject | Out-GridView
    

    This iterates through the properties of each of the resultant object and then creates a new object with those same properties but with the .Trim() method run on the name of each to remove any surrounding whitespace.

    This is obviously less efficient than just fixing the CSV file before you import, but doing that (generically) could also be tricky if you can't be certain where in the CSV the headerline appears (as it's not always the first).

    Of course if you just want to fix this one specific scenario, the other answer is simplest.