powershellazure-powershellexport-csv

Convert text File to CSV Format using powershell


I want to convert the Text File to CSV File and below is the Format using Powershell and need some assistance

Content for reference:

Quantity: 30
Manufacturer: Microsoft
License metric: Microsoft Core Infrastructure Server Suite Datacenter Core
Expiry: 31/12/2024

Quantity: 70
Manufacturer: Microsoft
License metric: Microsoft Windows Server Datacenter Core (SA)
Expiry: 31/12/2025

Quantity: 58
Manufacturer: Microsoft
License metric: Microsoft Core Infrastructure Server Suite Datacenter Core
Expiry: 31/12/2024

Convert Text File to CSV (into rows and columns) CSV Header: Quantity, Manufacturer, License metric, Expiry


Solution

  • Note:


    I suggest processing your file via the regex-based -split operator:

    # Create an ordered helper hashtable to help with [pscustomobject] construction
    $oht = [ordered] @{} 
    
    # Split the input file into blocks of lines, and process each block.
    (Get-Content -Raw file.txt) -split '\r?\n\r?\n' -ne '' | ForEach-Object { 
      $oht.Clear() # Clear the helper hashtable to start constructing a new object.
      # Split the block at hand into individual lines and process each.
      $_ -split '\r?\n' -ne '' | ForEach-Object {
        # Split the line at hand into property name and value...
        $name, $value = $_ -split ':', 2
        # ... and add this property-name pair to the helper hashtable.
        $oht[$name] = $value.Trim()
      }
      # Construct a [pscustomobject] from the helper hashtable and output it.
      [pscustomobject] $oht
    }  # | Export-Csv ...  # Add your Export-Csv call here.
    

    Display output, showing the constructed objects and their properties, using implicit table formatting:

    Quantity Manufacturer License metric                                             Expiry
    -------- ------------ --------------                                             ------
    30       Microsoft    Microsoft Core Infrastructure Server Suite Datacenter Core 31/12/2024
    70       Microsoft    Microsoft Windows Server Datacenter Core (SA)              31/12/2025
    58       Microsoft    Microsoft Core Infrastructure Server Suite Datacenter Core 31/12/2024
    

    Note: