none
add Header to CSV

    Question

  • Hello and Good day!

    I have a txt file and converted it to CSV but do not know how to add "USERID" header to my CSV File.

    $TXTFile = "C:\A.txt" 

    $CSVFile = "C:\B.csv" 

    #find all CNs in TXT file and list them in CSV File
    Select-String -Path $TXTFile  -Pattern 'CN=(.*?),' -AllMatches |
      Select-Object -Expand Matches |
      ForEach-Object { $_.Groups[1].Value } | 
      Out-File $CSVFile 

    Friday, February 9, 2018 12:04 PM

Answers

  • Hello,

    it is not enough to call a file ".csv" to get a csv. A csv is a comma separated file consisting of datasets (rows) with various properties (columns). 

    Out-File cmdlet is simply generating a text file. For generating csv use Export-CSV. But this will only work with an array of objects as imput. You simply have an array of strings.

    To get a single-property csv, you simply have to add "USERID" at the beginning of your array. Or you can create an object like this way:

    Select-String -Path $TXTFile  -Pattern 'CN=(.*?),' -AllMatches |
      Select-Object -Expand Matches |
      ForEach-Object { $_.Groups[1].Value } | 
      select @{L="UserID"; E={$_}} |
      Export-CSV $CSVFile -noTypeInformation


    • Edited by hpotsirhc Friday, February 9, 2018 12:16 PM
    • Marked as answer by frhling Friday, February 9, 2018 12:22 PM
    Friday, February 9, 2018 12:13 PM

All replies

  • Hello,

    it is not enough to call a file ".csv" to get a csv. A csv is a comma separated file consisting of datasets (rows) with various properties (columns). 

    Out-File cmdlet is simply generating a text file. For generating csv use Export-CSV. But this will only work with an array of objects as imput. You simply have an array of strings.

    To get a single-property csv, you simply have to add "USERID" at the beginning of your array. Or you can create an object like this way:

    Select-String -Path $TXTFile  -Pattern 'CN=(.*?),' -AllMatches |
      Select-Object -Expand Matches |
      ForEach-Object { $_.Groups[1].Value } | 
      select @{L="UserID"; E={$_}} |
      Export-CSV $CSVFile -noTypeInformation


    • Edited by hpotsirhc Friday, February 9, 2018 12:16 PM
    • Marked as answer by frhling Friday, February 9, 2018 12:22 PM
    Friday, February 9, 2018 12:13 PM
  • echo "header USERID" > c:yourfile.csv

    out-file -append


    Chris

    Friday, February 9, 2018 6:31 PM