ConvertFrom CSV - PowerShell
Overview
ConvertFrom-CSV converts the contents of a CSV file into a structured PowerShell object. It provides a convenient way to import tabular data and create structured objects for further processing and analysis.
Syntax
ConvertFrom-CSV [-Path] <String> [-Encoding] <Encoding> [-Delimiter] <Char> [-Header] [-Skip] <UInt32> [-MaximumLineNumber] <UInt32> [-OutputObject] <Object> [-InputObject] <Object> [-HeaderType] <HeaderType> [-NoCulture] -UseCulture
Options/Flags
- -Path: Specifies the path to the CSV file to convert.
- -Encoding: Sets the encoding used to read the CSV file. Default: Unicode.
- -Delimiter: Defines the character used as the field delimiter in the CSV file. Default: comma (,).
- -Header: Indicates whether the first row of the CSV file contains column headers. Default: false.
- -Skip: Skips the specified number of rows at the beginning of the CSV file.
- -MaximumLineNumber: Sets the maximum number of lines to read from the CSV file. Default: Unlimited.
- -OutputObject: Specifies the type of object to create. Default: PSObject.
- -InputObject: Accepts an existing object that contains CSV data.
- -HeaderType: Defines the type of headers present in the CSV file. Valid values: Inferred (default), None, UseFirstRow.
- -NoCulture: Parses numbers and dates without using culture-specific formatting.
- -UseCulture: Parses numbers and dates using culture-specific formatting.
Examples
Convert a CSV File to a List of Objects:
$objects = ConvertFrom-CSV -Path 'path/to/data.csv'
Converting with a Custom Delimiter:
$objects = ConvertFrom-CSV -Path 'path/to/pipe-delimited.csv' -Delimiter '|'
Skipping Header Row:
$objects = ConvertFrom-CSV -Path 'path/to/data.csv' -Header -Skip 1
Common Issues
- Malformed CSV Data: Ensure the CSV file is properly formatted with consistent delimiters and enclosed values.
- Encoding Problems: Verify that the encoding specified matches the actual encoding of the CSV file.
- Header Mismatches: Confirm that the headers in the CSV file correctly represent the field names of the desired objects.
Integration
Combining with Select-Object:
$filteredObjects = $objects | Select-Object -Property Name, Age
Creating a Data Table:
$dataTable = ConvertFrom-CSV -Path 'path/to/data.csv' -Header | Out-DataTable
Related Commands
- Import-Csv: Imports a CSV file into a PowerShell variable without creating objects.
- Export-Csv: Exports PowerShell objects to a CSV file.
- Out-DataTable: Creates a data table from a collection of objects.